Why is my jquery .on('change') not working for dynamically added selects

前端 未结 10 554
既然无缘
既然无缘 2020-12-31 01:12

I\'m adding select elements dynamically, like in the below HTML. I\'m not sure why the .on(\'change\' ...) is not working for the dynamic select. What am I missing?

<
10条回答
  •  孤独总比滥情好
    2020-12-31 01:59

    Came across this as I could not get my dynamically created selects which came back from an ajax post with dynamic id's, to trigger the event.

    $(document).on('change', 'select', function (e) {
        $("#theDiv select").on("change",function(){ post("SelectChanged");} );
    });
    

    This would not work until I had changed something first so I added

    $("#theDiv select").on("change",function(){ post("SelectChanged");} );
    

    However this not meant, that after the change, all other changes then fired twice. This may not be very good practice. But what I did was to to put in a function that is called at the start and each return of ajax.

     `function myFuncs(){
        $('#theDiv select').unbind('change');
        $('#theDiv select').on('change' function(){ post('selectChanged'); });
      }`
    

    But had to unbind at start of each function call else it doubled up the functions each time. I am sure there must be a proper way to do this, I just haven't found it yet. Thanks for starting the question.

提交回复
热议问题