dr.jekyllandme
dr.jekyllandme

Reputation: 623

How to dynamically update select source data

I have two select inputs, the first one has a list of options and based on what's selected, the 2nd select will change it's data. Initially, the 2nd select will have no values but it will dynamically change as the user selects values from the 1st select.

var sounds = {
                0:[{'id':0, 'text':'woof'}, {'id':1, 'text':'bark'}],
                1:[{'id':0, 'text':'meow'}, {'id':1, 'text':'purr'}],
                2:[{'id':0, 'text':'moo'}, {'id':1, 'text':'bellow'}]
             };
$('#select1').select2({
    data: [
               {'id':0, 'text':'DOG'},
               {'id':1, 'text':'CAT'},
               {'id':2, 'text':'COW'}
          ]
});
var select2_data = []
$('#select2').select2({
    data: select2_data
});

$('#select1').on("change", function(e) {
    data = $(this).select2('data');
    // Why doesn't this change data: in select2
    select2_data = sounds[data.id]
    $.each(select2_data, function(i, val) {
        console.log(val)
    });
});

In order to change select2's data, I assign the new list which data: is pointing to, but this doesn't work. I am still seeing empty values. What's going on?

Upvotes: 1

Views: 4009

Answers (1)

kannanrbk
kannanrbk

Reputation: 7144

Hope this would solve this problem.

http://jsfiddle.net/r7dhxt8e/6/

The only way to dynamically update to select2 is update select element options, select2 will listen for the changes and it will update it automatically.

    $(function() {
    var select1, select2, sounds, select2data = [];
    select1 = $("#select1"), select2 = $("#select2");
    sounds = { 0:[{'id':0, 'text':'woof'}, {'id':1, 'text':'bark'}],
              1:[{'id':0, 'text':'meow'}, {'id':1, 'text':'purr'}],
              2:[{'id':0, 'text':'moo'}, {'id':1, 'text':'bellow'}]
    };

    select1.select2({
        data:[
               {'id':0, 'text':'DOG'},
               {'id':1, 'text':'CAT'},
               {'id':2, 'text':'COW'}
          ],
        width:"200px"
    });
    select2.select2({
        data:select2data,
        width: "200px"
    });

    select1.on("change", function(e) {
       var data = $(this).select2('data');
       select2data = data && sounds[data[0].id];
       setSelect2Options(select2data);
    });

    function setSelect2Options(data) {
       if(!data) return;
       var i, l, html, opt;
       for(i = 0, l = data.length; i < l; i++) {
           opt = data[i];
           html += "<option value='"+ opt.id+"'>"+ opt.text + "</option>";
       }
       if(html) {
           select2.html(html);
       }
       select2.trigger('change');
    }
});

Upvotes: 2

Related Questions