如何使用jQuery来识别具有许多动态表单元素的“更改”事件

时间:2012-03-06 17:53:25

标签: jquery onchange

我有一个动态构建的Web表单,包含数十个/数百个表单元素文本字段。

有没有办法使用$().change(function(){});或其他方法来(a)唤起jQuery / Ajax在后台执行某些操作,以及(b)捕获哪些特定表单元素实际更改并使用其更改的值?

我可以处理Ajax部分。我对onChange事件没有成功。

感谢。

* JS文件看起来像 *

jQuery.support.cors = true; // needed for ajax to work in certain older browsers and versions

$(document).ready(function(){

    $('a[rel^="prettyPhoto"]').prettyPhoto({
        changepicturecallback: function() {
            //alert('have focus');
        }
    });


//find all the form elements in your form,
//then bind an event handler to all of the elements for the `change` event
$('#my-form').find('input, textarea').on('change', function (event) {

    //this now refers to the "changed" element

    var name  = this.name,
        value = this.value,
        id    = this.id,
        dObj  = {};//create object to pass as data parameter to AJAX request

    //set the key as the name of the input, and the value as the value of the input
    dObj[name] = value;

    $.ajax({
        url     : '<url>',
        data    : dObj,//pass the data object
        //success : function (data) { ... },
        success : alert('changed CCC'),
        error   : function (jqXHR, textStatus, errorThrown) { /*don't for get to deal with errors*/ }
    });
});


$('#my-form').on('change', 'input, textarea', function (event) {
    alert('changed AAA');
});



$(document).on('change', '#my-form input, #my-form textarea', function (event) {
    alert('changed BBB');
});



}); // end .ready()

//  window.parent.closePP();

1 个答案:

答案 0 :(得分:6)

//find all the form elements in your form,
//then bind an event handler to all of the elements for the `change` event
$('#my-form').find('input, textarea').on('change', function (event) {

    //this now refers to the "changed" element

    var name  = this.name,
        value = this.value,
        id    = this.id,
        dObj  = {};//create object to pass as data parameter to AJAX request

    //set the key as the name of the input, and the value as the value of the input
    dObj[name] = value;

    $.ajax({
        url     : '<url>',
        data    : dObj,//pass the data object
        success : function (data) { ... },
        error   : function (jqXHR, textStatus, errorThrown) { /*don't for get to deal with errors*/ }
    });
});

更新

如果在页面加载后添加元素,则可以使用事件委托绑定到DOM中的元素:

$('#my-form').on('change', 'input, textarea', function (event) {
    ...
});

这假设绑定时#my-form在DOM中,否则您可以绑定到document

$(document).on('change', '#my-form input, #my-form textarea', function (event) {
    ...
});