Search code examples
javascriptjqueryjquery-chosen

Change options in select with JavaScript without loosing chosen


I'm trying to reload the options list of a select with JavaScript and JQuery, but I need to preserve previous chosen values.

This is my code:

    var temp = $('#SelectName').chosen().val();

    select = document.getElementById('SelectName');

    if (select.options.length > 0) {
        $('#SelectName').find('option').remove();
    }

    for (var i = 0; i < result.length; i++) {
        var option = document.createElement('option');
        option.value = result[i].myIdVariable;
        option.text = result[i].myTextVariable;
        select.appendChild(option); 
    }

    $('#SelectName').chosen(temp);

    $('#SelectName').trigger('chosen:updated');

With this code I loose all the chosen values.


Solution

  • I solved with this code:

    var temp = $('#SelectName').val();
    
    select = document.getElementById('SelectName');
    
    if (select.options.length > 0) {
        $('#SelectName').find('option').remove();
    }
    
    for (var i = 0; i < result.length; i++) {
        var option = document.createElement('option');
        option.value = result[i].myIdVariable;
        option.text = result[i].myTextVariable;
        select.appendChild(option); 
    }
    
    $('#SelectName').val(temp);
    
    $('#SelectName').trigger('chosen:updated');
    

    The difference is that now I use:

    var temp = $('#SelectName').val();
    

    and

    $('#SelectName').val(temp);
    

    previously:

    var temp = $('#SelectName').chosen().val();
    

    and

    $('#SelectName').chosen(temp);