[javascript] select2 changing items dynamically

I have two selects that are linked: Each value of the first select determines which items will be displayed in the second select.

The values of the second select are stored in a two-dimension array:

[ [{"id":1,"text":"a"}, {"id":2,"text":"b"},...],
  [{"id":"1a","text":"aa"},{"id":"1b","text":"ba"},...],
  ...
]

The first select value determines the index to be used to populate the second select. So in a 'change' event on the first I should be able to modify the items select-two contains.

Reading documentation I think I need to use the "data" option... but not shure how as the example loads the array data on initialization and it seems to don't work if I try to do the same after initialization.

HTML

Attribute:
<select name="attribute" id="attribute">
    <option value="0">Color</option>
    <option value="1">Size</option>
</select>

Value:
<select name="value" id="value"></select>

<script>
   var data = [ [{"id":1,"text":"black"}, {"id":2,"text":"blue"},...],
                [{"id":"1","text":"9"},{"id":"1","text":"10"},...],
              ];
   $('#attribute').select2().bind('change', function(){
      // Here I need to change `#value` items.
      $('#value').select2('data',data[$(this).val()]);  // This does not work
   );

   $('#value').select2();
</script>

This question is related to javascript jquery-select2

The answer is


In my project I use following code:

$('#attribute').select2();
$('#attribute').bind('change', function(){
    var $options = $();
    for (var i in data) {
        $options = $options.add(
            $('<option>').attr('value', data[i].id).html(data[i].text)
        );
    }
    $('#value').html($options).trigger('change');
});

Try to comment out the select2 part. The rest of the code will still work.


I'm successfully using the following to update options dynamically:

$control.select2('destroy').empty().select2({data: [{id: 1, text: 'new text'}]});


I fix the lack of example's library here:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js">

http://jsfiddle.net/bbAU9/328/


Try using the trigger property for this:

$('select').select2().trigger('change');

For v4 this is a known issue that won't be addressed in 4.0 but there is a workaround. Check https://github.com/select2/select2/issues/2830