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"},...],

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.


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

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

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




I've made an example for you showing how this could be done.

Notice the js but also that I changed #value into an input element

<input id="value" type="hidden" style="width:300px"/>

and that I am triggering the change event for getting the initial values

$('#attribute').select2().on('change', function() {

Code Example


In the current version of select2 the class attribute is being transferred from the hidden input into the root element created by select2, even the select2-offscreen class which positions the element way outside the page limits.

To fix this problem all that's needed is to add removeClass('select2-offscreen') before applying select2 a second time on the same element.

$('#attribute').select2().on('change', function() {

I've added a new Code Example to address this issue.


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

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


Try using the trigger property for this:


I fix the lack of example's library here:

<link href="" rel="stylesheet"/>
<script src="">


For v4 this is a known issue that won't be addressed in 4.0 but there is a workaround. Check


In my project I use following code:

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

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


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.