Javascript 整个表格 onChange

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10760847/
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-24 02:49:21  来源:igfitidea点击:

Entire form onChange

javascript

提问by Mori

How can I use onChangeor a similar event for all formelements? I don't want to use onChangefor each field separately.

我如何onChange为所有form元素使用或类似的事件?我不想onChange分别用于每个字段。

回答by Mori

You can use the changeevent on the formelement:

您可以changeform元素上使用事件:

var form = document.querySelector('form');
form.addEventListener('change', function() {
    alert('Hi!');
});

回答by Steve

If you are using jQuery, you can use the changeevent on the form element, because in jQuery the event bubbles up.

如果您使用 jQuery,则可以change在表单元素上使用该事件,因为在 jQuery 中,事件会冒泡。

$('#formId').change(function(){...});

If you are using plain javascript, the change event does not bubble (at least not cross browser). So you would have to attach the event handler to each input element separately:

如果您使用普通的 javascript,则更改事件不会冒泡(至少不会跨浏览器)。因此,您必须分别将事件处理程序附加到每个输入元素:

var inputs = document.getElementsByTagName("input"); 
for (i=0; i<inputs.length; i++){
   inputs[i].onchange = changeHandler;
}

(of course, you would have to do a similar thing to all selects and textareas)

(当然,您必须对所有选择和文本区域做类似的事情)