Note that there are some explanatory texts on larger screens.

plurals
  1. POAdding an EventListener to a form, running a function on submit on whatever child <input> in the form actually called the submit
    primarykey
    data
    text
    <p><a href="http://jsfiddle.net/twG6R/8/" rel="nofollow noreferrer">http://jsfiddle.net/twG6R/8/</a></p> <p>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.</p> <p>So, I have a <code>&lt;form&gt;</code> with two <code>&lt;input&gt;</code> fields in it. I have an eventListener stuck to the <code>&lt;form&gt;</code> 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.</p> <p>What can I do?</p> <p>EDIT: Should I look at all the child elements of <code>form</code> somehow and test each child to see if there's something in it, and then call <code>alertGrade</code> with the non-empty children as a parameter?</p> <p>HTML:</p> <pre><code>&lt;form id="form"&gt; &lt;input type="number" id="score1" value="" min="0" max="100"&gt; &lt;input type="number" id="score2" value="" min="0" max="100"&gt; &lt;input type="submit" value="Grade"&gt; &lt;/form&gt; </code></pre> <p>JavaScript:</p> <pre><code>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); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload