Search code examples
javascriptjqueryjquery-ui-multiselect

How to generate option values into jquery multiselect from js


i was trying to generate dynamically option values in my jquery multiselect using javascript.

function prova(data){
      var t = 0;
      var tmp = new Array();
      var keys = new Array();
      $("#select-1").multiselect({
      multiple: true,
      header: true,
      noneSelectedText: "Select an Option",
      selectedList: 1
    });
    var stringa ="";
    $.each(data, function(key,value){
    stringa +="<option value=\""+key+"\">"+key+"</option>";
    if(t==0){
    tmp[0] = key;
    }
    t++;
    });
    $("#select-1").html(stringa);
}

My values generated in the #select-1 are something like that:

<select id="select-1" size="5" name="example-basic" title="Basic example" style="display: none;">
<option value="name1">name1</option>
<option value="name2">name2</option>
<option value="name3">name3</option>
<option value="name4">name4</option>
<option value="name5">name5</option>
</select>

The problem is that it doesn't fill the option values into the jquery multiselect, that remains empty.


Solution

  • Because you are using .html() directly on the element, you are replacing the elements inside it before inserting the new elements. You might want to use .append() like:

    $.each(data, function(key,value){
        stringa +="<option value=\""+key+"\">"+key+"</option>";
        if(t==0){
        tmp[0] = key;
        }
        t++;
        });
        $("#select-1").append(stringa);
    

    Or use the previous values as well, in the .html() usage like:

     $.each(data, function(key,value){
        stringa +="<option value=\""+key+"\">"+key+"</option>";
        if(t==0){
        tmp[0] = key;
        }
        t++;
        });
        $("#select-1").html($("#select-1").html()+stringa);