5

What I am doing: Dynamically adding options to a select box when modal popup opens. And waiting for on change trigger to respond.

Observation: It pops up alert box for all options but first. Below is the code.

$("#query_product").on("change", function(e){
  alert(1)
});

$("#add_condition_modal").on( "shown.bs.modal", function() {
  options = ['<option>one</option>','<option>two</option>','<option>three</option>']
  $('#query_product').find('option').remove()
  $('#query_product').append(options); 
});

<select id="query_product" name="query_product" required></select>

Another Observation: When I prefill the html select box with same options and then select the first option or any option, I see the alert popup. Now I am confused.

I tried using event delegation for dynamically added elements.

$(document).on("change","#query_product", function() {

Nothing seems to work. Any help will be appreciated. TIA

bill_cosby
  • 145
  • 2
  • 9

2 Answers2

4

Try this:

$("#query_product").on("change", function(e){
  alert(1)
});

$("#add_condition_modal").on( "shown.bs.modal", function() {
  options = ['<option value="one">one</option>','<option value="two">two</option>','<option value="three">three</option>']
  $('#query_product').find('option').remove();
  $('#query_product').append(options); 
  $('#query_product').val("");
});

<select id="query_product" name="query_product" required></select>
1

Here's you're doing it bit wrong.

['<option>one</option>','<option>two</option>','<option>three</option>']
I'd suggest use string.

$("#query_product").on("change", function(e){
  alert(1)
});

$("#add_condition_modal").on( "shown.bs.modal", function() {
  options ='<option>one</option><option>two</option><option>three</option>';
  $('#query_product').html(options);
});

<select id="query_product" name="query_product" required></select>

When you're using remove() jQuery function it removes the select2 as well. so reinitializing would be fix for you.

Note: If you want to use array of options then do it like this.

var options = ['first_option','second_option','third_option'];
var optionString = '';
    for(var i = 0; i< options.length; i++){
        optionString += '<option>'+options[i]+'</option>';
    }
 then $('#selector').html(optionString);

Here's a Fiddle that might help https://jsfiddle.net/imrealashu/61tvh76t/3/

imrealashu
  • 5,089
  • 4
  • 16
  • 28