Search code examples
javascriptjqueryjquery-mobilemultiple-select

JQuery mobile - how to set the values of a multiple select?


I have a multiple select in jquery mobile.

docs: http://jquerymobile.com/demos/1.0a4.1/docs/forms/forms-selects.html

To get the value I do this

    var leerplandoelen = $("#AddLessonForm_leerplandoelen").val();

        var leerplandoelenString = "";
        if(leerplandoelen != null){
            $.each(leerplandoelen, function(i, le){
                if(i!=leerplandoelen.length-1){
                    leerplandoelenString += "\""+le+"\",";
                }else{
                    leerplandoelenString += "\""+le+"\"";
                }
            });
        }

To get a string like this '"1", "2", "3"'.

How can I set the values?

I tried the following:

    $('#AddLessonForm_leerplandoelen').val(['3','6','14']).selectmenu('refresh');

But it didn't work.


Solution

  • Do it this way, read array of selected items. Mark option selected based on value

    // array of values
    var selected = ["2", "4"];
    
    $.each(selected, function (i, v) {
    
      // mark options selected
      $("select option[value='" + v + "']").prop("selected", true);
    
      // refresh selectmenu
      $("select").selectmenu("refresh");
    
    });
    

    Demo