简体   繁体   中英

After dynamical adding options to select box, trigger doesn't work

I have select box with with id test . I have trigger on it like:

$("#test").on('change', function() { alert('test'); })

And that works for the first time, but after I add some options to select box dynamically like:

var option = $("<option>")
          .attr('value', this.value)
          .attr('class', this.class)
          .html(this.text);

        // if id corresponds to selected id then select it
        if (parseInt(this.value) == selected_id) {
          option.attr('selected', 'selected');
        }

        // append to select
        $("#test").append(option);

trigger doesn't work. What to do?

This should do it:

$(document).on('change', '#test', function() { alert('test'); });

With the following:

    var trigger = false;
    if (parseInt(this.value) == selected_id) {
      option.attr('selected', 'selected');
      trigger = true;
    }

    // append to select
    $("#test").append(option);
    !trigger || $('#test').change();

NOTE: By just adding a selected attribute to a new option, the select element won't trigger. You have to explicitly trigger it using .change() or .trigger('change') when applicable. When a user manually selects a value, both the value is set and the change event is triggered at the same time (if the new value is not equal to the previous value).

Try this:

var option = " <option value='"+this.value+"' class='"+this.class+"'>"+this.text+"</option> "; $("#test").append(option) ;

Instead of doing:

var option = $("<option>")
          .attr('value', this.value)
          .attr('class', this.class)
          .html(this.text);

And then appending it.

Could you post the entire script? Or at least a more complete example?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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