2

This is the code that is working (but repetitive). I tried to replace the "getElementById" part with "getElementsByClassName", adding a class to the elements - but that didn't do it for me. Right now I have this anonymous function repeated once for each ID:

document.getElementById("gasCost").onkeypress = function(e) {
    if(e.keyCode == 13) {
        goButton();
    }
}

HTML:

<input placeholder="How far are you going? (miles)" id="distance">
<input placeholder="How many MPG does your car get?" id="mileage">
<input placeholder="What's the average cost of gas?" id="gasCost">

Is it possible to define the function prior & call it to each ID? Is it possible to do it differently with classes? I'm open to all suggestions, but I'd prefer not to be using jQuery.

kfrncs
  • 433
  • 3
  • 15
  • 1
    What about Prototype? It's bad practice to extend html elements but with Prototype you can do just this. – Phix Nov 06 '13 at 06:13
  • Thanks for the tip! I'm trying to avoid frameworks as I'm pretty early in the learning process. I want to build a solid foundation first. I will add it to my list of frameworks to get around to once I understand JS. – kfrncs Nov 06 '13 at 06:29

2 Answers2

3

If you wanted to use classes you could do something like this:

function keyHandler(e) {
    if(e.keyCode == 13) {
        goButton();
    }
}
var elements = document.getElementsByClassName("yourclasshere");
for (var i = 0; i < elements.length; i++)
    elements[i].onkeypress = keyHandler;

(getElementsByClassName() returns a list, so you have to loop over each element in the list and bind a handler to them individually.)

Alternatively you could bind a single handler to a parent element that contains all of your inputs (perhaps to a form element?):

document.getElementById("someContainer").onkeypress = function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    if (e.keyCode === 13 && e.target.tagName === "INPUT") {
        goButton();
    }
};

Demo: http://jsfiddle.net/9U9nn/

This works because the key events "bubble up" from the source element (your input) through all containers until they reach the document. (So, worst case, you could bind the handler directly to the document.) You can tell which element the event originated with by checking the event.target (or event.srcElement for older IE).

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
-1
function submitOnEnter(e) {
    if(e.keyCode == 13) {
        goButton();
    }
}

document.getElementById("gasCost").onkeypress = submitOnEnter;
document.getElementById("mileage").onkeypress = submitOnEnter;

Note that this is already the default behavior in HTML forms: pressing enter submits the form.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121
  • Ah, the issue was that I had it written as submitOnEnter(); - Can anyone explain precisely what the parentheses do to break this? – kfrncs Nov 06 '13 at 06:18