Entire form onChange

前端 未结 2 978
走了就别回头了
走了就别回头了 2020-12-05 12:52

How can I use onChange or a similar event for all form elements? I don\'t want to use onChange for each field separately.

相关标签:
2条回答
  • 2020-12-05 13:15

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

    $('#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:

    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)

    0 讨论(0)
  • 2020-12-05 13:16

    You can use the change event on the form element:

    var form = document.querySelector('form');
    form.addEventListener('change', function() {
        alert('Hi!');
    });
    
    0 讨论(0)
提交回复
热议问题