简体   繁体   English

整个表格onChange

[英]Entire form onChange

How can I use onChange or a similar event for all form elements? 如何为所有form元素使用onChange或类似事件? I don't want to use onChange for each field separately. 我不想单独为每个字段使用onChange

If you are using jQuery, you can use the change event 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). 如果您使用普通的javascript,则更改事件不会冒泡(至少不会跨浏览器)。 So you would have to attach the event handler to each input element separately: 因此,您必须将事件处理程序分别附加到每个输入元素:

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) (当然,你必须对所有选择和textareas做类似的事情)

You can use the change event on the form element: 您可以在form元素上使用change事件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM