Javascript 将 EventListener 添加到表单,在表单中实际调用提交的任何子 <input> 上运行提交函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6715354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:54:21  来源:igfitidea点击:

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

javascripthtml

提问by Austin Yun

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

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.

所以,我有<form>两个<input>字段。我有一个 eventListener 一直在<form>监听“提交”事件。然后我想运行一个函数,该函数对用户输入的 input1 或 input2 的数字执行一些操作。用户在例如 input2 中键入一个数字,按回车键,然后函数调用 this.id,但返回表单的 id,而不是作为表单子项的实际输入框。

What can I do?

我能做什么?

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

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

HTML:

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:

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

采纳答案by Ankit

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.

这将遍历表单的每个 childNodes,如果它发现某些东西具有该值,它会将其值发送到 alertGrade。如果它没有找到任何东西,它会提醒用户输入一些东西。

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.

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

回答by aroth

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

你试过event.srcElement吗?因为我做到了,令人沮丧的是它没有按预期工作。

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

我可以在不使用原生 JavaScript 的情况下提出的最简单的解决方案是向keypress输入字段添加一个侦听器,并使用它来捕获和手动处理return按键,例如:

<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/

示例:http: //jsfiddle.net/q8Eqn/

回答by bbg

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 onchangeevent (slightly less involved than reading each keypress):

像其他受访者一样,我也不知道是否有办法完全按照您的意愿行事。但是您可以找出输入字段何时随onchange事件发生变化(比读取每个按键稍微少一些):

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

回答by WordsWorth

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

根据我的理解,您需要 score1 或 score2 的值。那么您应该在 alertGrade() 的函数调用中传递 id“score1”和“score2”

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

当您调用 alrtGrade(this.id) 时。它实际上是在传递表单的 id。

OR

或者

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

当您调用 getElementById 时,id 应该是“score1”或“score2”