2

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.

1
  • In the example where you showed what your #select-1 is like, I see the value and innerHTML of each option element. Did you mean to show the option elements with no value? You may want to modify your question to show that for clarity because as far as we can tell, it is working as it should. Commented Apr 22, 2015 at 18:41

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.