Austin Yun Austin Yun - 4 years ago 80
HTML Question

Adding an EventListener to a form, running a function on submit on whatever child <input> in the form actually called the submit

http://jsfiddle.net/twG6R/8/

Ignore the fact that this is a completely toy application. If there is NO time in which this is the right way to do things however, let me know.

So, I have a

<form>
with two
<input>
fields in it. I have an eventListener stuck to the
<form>
listening for a "submit" event. I then want to run a function which does some stuff to the number the user put in either input1 or input2. User types a number in say, input2, hits enter, and the function calls on this.id, but returns the id of the form, not the actual input box that is a child of the form.

What can I do?

EDIT: Should I look at all the child elements of
form
somehow and test each child to see if there's something in it, and then call
alertGrade
with the non-empty children as a parameter?

HTML:

<form id="form">
<input type="number" id="score1" value="" min="0" max="100">
<input type="number" id="score2" value="" min="0" max="100">
<input type="submit" value="Grade">
</form


JavaScript:

function alertGrade(elementID) {
var score = document.getElementById(elementID).value;
var grade = calculateGrade(score);
alert("Score of " + score + ": " + grade);
}

function loaded() {
document.getElementById("form").addEventListener("submit",
function(event) {
event.preventDefault();
// this.id will show "form"
alert(this.id);
alertGrade(this.id);},
false);
}

window.addEventListener("load", loaded, false);

Answer Source

You can use something like:

function loaded(){
    document.getElementById('form').addEventListener("submit", function(){
        for(var i=0, j=this.childNodes.length; i<j, i++){
            if(this.childNodes[i].value !== ""){
               alertGrade(this.childNodes[i].id);
               return;
           }
       }
       alert("Please type something");
    }, false);
}

This will loop through each of the childNodes of the form and if it finds something has the value, it will send its value to alertGrade. If it does not find anything, it will alert the user to type something.

But a word of caution: Everytime the user clicks submit button, the page refreshes (atleast on my browser) and you may not get what you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download