JQuery multiselect - Set a value as selected in th

2019-01-06 09:54发布

I am having a multiselect dropdown as below

<select id="data" name="data" class="data" multiple="multiple">
  <option value="100">foo</option>
  <option value="101">bar</option>
  <option value="102">bat</option>
  <option value="103">baz</option>
</select>

On load of page, i will get an array of value like [101,102]. I should iterate through the array and make the values selected(check boxes corresponding to the ids should be checked). Please help.

16条回答
Fickle 薄情
2楼-- · 2019-01-06 10:31

Thank you all for your answers.

Taking all of your answers as a guideline, I resolved the problem with the below code:

var valArr = [101,102];
i = 0, size = valArr.length;
for(i; i < size; i++){
  $("#data").multiselect("widget").find(":checkbox[value='"+valArr[i]+"']").attr("checked","checked");
  $("#data option[value='" + valArr[i] + "']").attr("selected", 1);
  $("#data").multiselect("refresh");
}

Thanks once again for all your support.

查看更多
叼着烟拽天下
3楼-- · 2019-01-06 10:32
var valArr = [101,102], // array of option values
    i = 0, size = valArr.length, // index and array size declared here to avoid overhead
    $options = $('#data option'); // options cached here to avoid overhead of fetching inside loop

// run the loop only for the given values
for(i; i < size; i++){
    // filter the options with the specific value and select them
    $options.filter('[value="'+valArr[i]+'"]').prop('selected', true);
}

Here is a demo

查看更多
SAY GOODBYE
4楼-- · 2019-01-06 10:34
$("#dropDownId").val(["130860","130858"]);
$("#dropDownId").selectmenu('refresh');
查看更多
来,给爷笑一个
5楼-- · 2019-01-06 10:35
 var valArr = ["1","2","3"];

/* Below Code Matches current object's (i.e. option) value with the array values */
 /* Returns -1 if match not found */
 $("select").multiselect("widget").find(":checkbox").each(function(){
    if(jQuery.inArray(this.value, valArr) !=-1)
            this.click();

   });

This selects the options whose value matches with values in array.

查看更多
放我归山
6楼-- · 2019-01-06 10:40

work fine for me ,change ids according to you requirement.

$("#FormId select#status_id_new").val('');
 $("#FormId select#status_id_new").multiselect("refresh");
查看更多
太酷不给撩
7楼-- · 2019-01-06 10:44
//Do it simple

var data="1,2,3,4";

//Make an array

var dataarray=data.split(",");

// Set the value

$("#multiselectbox").val(dataarray);

// Then refresh

$("#multiselectbox").multiselect("refresh");
查看更多
登录 后发表回答