最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

/

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);

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);
Share Improve this question edited Nov 24, 2016 at 20:30 Joeytje50 19.1k15 gold badges67 silver badges99 bronze badges asked Jul 16, 2011 at 4:36 Austin YunAustin Yun 4891 gold badge5 silver badges14 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 7

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.

Have you tried event.srcElement? Because I did, and frustratingly it did not work as expected.

The simplest solution I could come up without using native JavaScript was to add a keypress listener to the input fields, and use that to catch and manually handle the return keypress, like:

<input type="number"
      onkeypress="return inputKeyPress(event, this);"
      id="score1"
      value=""
      min="0" max="100">

function inputKeyPress(evt, field) {
    var evt  = (evt) ? evt : ((event) ? event : null);

    if (evt.keyCode == 13) {
        alertGrade(field.id);
        return false;
    }

    return true;
}

Example: http://jsfiddle.net/q8Eqn/

Like the other respondents, I also don't know if there's a way to do precisely what you want. But you can find out when an input field changes with the onchange event (slightly less involved than reading each keypress):

document.getElementById("score1").addEventListener("change",
        function(event) {
            alert(this.id);
        }, false);

As per my understanding you want value of score1 or score2.Then you should pass id "score1" and "score2" in your function call of alertGrade()

when you call alrtGrade(this.id).It is actually passing the id of form.

OR

when you call getElementById,the id should be either "score1" or "score2"

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论