Jquery .change() function not working with dynamically populated SELECT list

前端 未结 7 893
灰色年华
灰色年华 2020-12-05 14:13

I have a select field that is dynamically populated with an ajax call that simply returns all the HTML select options. Here is the part of the PHP that just echo\'s the sel

相关标签:
7条回答
  • 2020-12-05 14:23

    try .live: http://docs.jquery.com/Events/live

    From docs: Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.

    0 讨论(0)
  • 2020-12-05 14:24

    An example using .live()

    $('#my_form_id select[name^="my_select_name"]').live('change', (function () {
        console.log( $("option:selected", this).val());
        })
     );
    
    0 讨论(0)
  • 2020-12-05 14:25

    Just commented on your last question...Here's what I said:

    Use jQuery bind

    function addSelectChange() {
       $('select').bind('change', function() {
           // yada yada
       });
    } 
    

    Call addSelectChange in your ajax success function. It should do the trick. Take a look at jQuery live event too (for when you want to set events for all current and future DOM elements in a later project or something). Unfortunately the change event and a few others aren't yet supported with live. Bind is the next best thing

    0 讨论(0)
  • 2020-12-05 14:28

    Use delegate() function instead. More about that here http://www.elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/

    0 讨论(0)
  • 2020-12-05 14:33

    I found as solution to make only

    <select id="myselect"></select> 
    

    in php/html file and then generate options for it by ajax:

    $.post("options_generator.php", function (data) { $("#myselect").append(data); });
    

    In options_generator.php echo options only:

    echo "<option value='1'>1</option>";
    echo "<option value='2'>2</option>";
    
    0 讨论(0)
  • 2020-12-05 14:36

    A more up to date answer..

    Since the elements are dynamically populated, you are looking for event delegation.

    Don't use .live()/.bind()/.delegate(), though. You should use .on().

    According to the jQuery API docs:

    As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on().

    Therefore you would use something like this:

    $(document).on('change', 'select', function (e) {
        /* ... */
    });
    
    0 讨论(0)
提交回复
热议问题