将EventListener添加到表单,在提交中运行一个函数,在实际上称为提交的表单中的任何子<input>

Aus*_*Yun 6 html javascript

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

忽略这是一个完全玩具应用程序的事实.如果没有时间这是正确的做事方式,请告诉我.

所以,我有<form>两个<input>字段.我有一个eventListener坚持<form>听"提交"事件.然后我想运行一个函数,它对用户放入input1或input2的数字做一些事情.用户输入一个数字,例如input2,命中enter,函数调用this.id,但返回表单的id,而不是表单子项的实际输入框.

我能做什么?

编辑:我应该form以某种方式查看所有子元素并测试每个孩子以查看其中是否有某些内容,然后alertGrade使用非空子项作为参数调用?

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>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

Ank*_*kit 6

您可以使用以下内容:

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);
}
Run Code Online (Sandbox Code Playgroud)

这将循环遍历表单的每个childNodes,如果找到具有该值的内容,它将将其值发送到alertGrade.如果没有找到任何内容,它会提醒用户输入内容.

但请注意:每次用户单击"提交"按钮时,页面都会刷新(至少在我的浏览器上),您可能无法获得所需内容.