JQuery Bootstrap Multiselect plugin - Set a value as selected in the multiselect dropdown
Asked Answered
E

17

58

I am having a multiselect dropdown using the Boostrap Multiselect plugin (http://davidstutz.de/bootstrap-multiselect/) 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.

Erbium answered 6/8, 2011 at 10:43 Comment(4)
Checkboxes? What checkboxes?Eh
Each item in the dropdown will have a checkbox. On selecting the item, the check box will come as checked.Erbium
Thanks you all for your answers. Taking all your answers as 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.Erbium
Good question, I don't like the selected answer, though.Revivify
E
25

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.

Erbium answered 9/8, 2011 at 12:1 Comment(5)
$("#data option[value='" + valArr[i] + "']").attr("selected", 1); Just that part for mu purposes. Thanks guys.Neapolitan
multiselect() is not defined anywhere in JQuery documentation? api.jquery.com/?s=multiselectRevivify
Refresh didn't work for me. If you have the same problem try reload instead.Noakes
I referred your solution, this worked for me $('#multiSelect').val(valueToBeSet).multiselect('refresh');Olathe
@K.Shaikh thank you so much this is the only thing that has worked for me!Hope
S
159
//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");
Subaltern answered 17/6, 2012 at 6:40 Comment(7)
What is the #multiselectbox ?Marinate
@Marinate the dropdown element.Monda
$("#ddl_multiselect").trigger("change"); using this instead of refresh worked for me.Alanna
multiselect() is not a jQuery function: api.jquery.com/?s=multiselect All I get is "multiselect is undefined." Yatin's answer below is both simpler and actually works.Revivify
@TaponSayeem its really very helpful nice and clean codeGorski
The issue for me was that refresh doesn't work try reload instead. This may have to do with different libs or different versions. $("#multiselectbox").multiselect("reload");Noakes
This should be the accepted answer. Thanks!Maniac
E
25

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.

Erbium answered 9/8, 2011 at 12:1 Comment(5)
$("#data option[value='" + valArr[i] + "']").attr("selected", 1); Just that part for mu purposes. Thanks guys.Neapolitan
multiselect() is not defined anywhere in JQuery documentation? api.jquery.com/?s=multiselectRevivify
Refresh didn't work for me. If you have the same problem try reload instead.Noakes
I referred your solution, this worked for me $('#multiSelect').val(valueToBeSet).multiselect('refresh');Olathe
@K.Shaikh thank you so much this is the only thing that has worked for me!Hope
S
20

It's supposed to be as simple as this:

<select id='multipleSelect' multiple='multiple'>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
<script type='text/javascript'>
    $('#multipleSelect').val(['1', '2']);
</script>

Check my Fiddle: https://jsfiddle.net/luthrayatin/jaLygLzo/

Stonge answered 14/6, 2016 at 2:30 Comment(1)
Yes! So elegant!Sauveur
C
10
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

Charente answered 6/8, 2011 at 11:4 Comment(0)
P
6

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

$("#FormId select#status_id_new").val('');
 $("#FormId select#status_id_new").multiselect("refresh");
Phox answered 25/1, 2017 at 14:16 Comment(1)
In my case it was much simpler: $("#listContent").val(4001); ThksFrederickfredericka
L
4

that code should help:

var selected=[101,103];
var obj=$('#data');
for (var i in selected) {
    var val=selected[i];
    console.log(val);
   obj.find('option:[value='+val+']').attr('selected',1);
}
Lithic answered 6/8, 2011 at 11:0 Comment(0)
S
4

from a php array into the multiselect...

$PHP_array=array();           // create array anyway you need to in PHP
array_push($PHP_array,20);    // Single ID values
array_push($PHP_array,22);

$javascript_str = json_encode($PHP_array);   // JSON ENCODE        

// then in the JS script

$("#multiselectbox").val(<?php echo $javascript_str; ?>);

// Then refresh

$("#multiselectbox").multiselect("refresh");
Sarene answered 31/3, 2015 at 23:8 Comment(0)
M
3
 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.

Magnesia answered 14/2, 2013 at 11:23 Comment(0)
T
2

The official site has mentioned (in "Manually check or uncheck a checkbox?" section) just to use click()

e.g.

$("#ddl_singleSelect")
    .multiselect("widget")
        .find(":radio[value='']").click();  // change displayed selectedText
$("#ddl_singleSelect option[value='']")
    .prop("selected", true)             // change val()
    .trigger("change");                 // fire change event


$("#ddl_multiselect").multiselect("uncheckAll");    // init by de-selecting all
$("#ddl_multiselect")
    .multiselect("widget")
        .find(     ":checkbox[value='1']"
                + ",:checkbox[value='2']"
                + ",:checkbox[value='3']"
                + ",:checkbox[value='4']"
            ).click();  // change displayed selecetdText
$("#ddl_multiselect")
    .find(     "option[value='1']"
            + ",option[value='2']"
            + ",option[value='3']"
            + ",option[value='4']"
        ).prop("selected", true);   // change val()
$("#ddl_multiselect").trigger("change");    // fire change event

OR by HTML

<select name="example-presets" multiple="multiple" size="5">
    <option value="option1" selected="selected">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="option3" selected="selected">Option 3</option>
    <option value="option4" selected="selected">Option 4</option>
    <option value="option5" disabled="disabled">Option 5</option>
    <option value="option6" disabled="disabled">Option 6</option>
    <option value="option7">Option 7</option>
    <option value="option8">Option 8</option>
    <option value="option9">Option 9</option>
</select>
....
<script type="text/javascript">$("select").multiselect();</script>
Thrilling answered 17/3, 2016 at 3:15 Comment(0)
K
2

I got a better solution from jquery-multiselect documentation.

var data = [101,102];

$("#data").multiSelect('deselect_all');

$("#data").multiSelect("select",data);
Karyosome answered 19/4, 2017 at 12:53 Comment(1)
this and Basant answer below works, but behave a bit different, test them and choose which behaviour suite your UIGraz
L
0

I hope these functions will help you.

$('#your-select').multiSelect('select', String|Array);

$('#your-select').multiSelect('deselect', String|Array);

$('#your-select').multiSelect('select_all');

$('#your-select').multiSelect('deselect_all');

$('#your-select').multiSelect('refresh');

Reference by this site Reference

Lemay answered 6/8, 2011 at 10:43 Comment(0)
I
0
$("#dropDownId").val(["130860","130858"]);
$("#dropDownId").selectmenu('refresh');
Inclusive answered 9/5, 2013 at 6:28 Comment(0)
D
0

this is my code sample. I have comma separated numbers for multi select drop down and want to select options multiple options from comma separated values.

var selected_tags_arr = new Array();
var selected_tags = 1,2,4;
selected_tags_arr = selected_tags.split(",");
$('#contact_tags option').each(function (){
    var option_val = this.value;
    for (var i in selected_tags_arr) {
        if(selected_tags_arr[i] == option_val){
            $("#contact_tags option[value='" + this.value + "']").attr("selected", 1);
        }
    }
});
Ditto answered 15/1, 2014 at 11:27 Comment(0)
S
0

This is what worked from me using an array as input. First uncheck all options, then click on the chosen options using jquery

var dimensions = ["Dates","Campaigns","Placements"];

$(".input-dimensions").multiselect("uncheckAll");

for( var dim in dimensions) {
  $(".input-dimensions").multiselect("widget")
    .find(":checkbox[value='" + dimensions[dim] + "']").click();
}
Synchroflash answered 23/1, 2014 at 19:31 Comment(0)
S
0

I ended up having to make a slight change using the click event on the input element by also setting the checked prop after firing the click event.

$(y.Ctrl).multiselect("widget").find(":checkbox").each(function () {
    if ($.inArray(this.value, uniqueVals) != -1) {
        $(this).click();
        $(this).prop('checked', true);
    }
});
Smoko answered 21/10, 2015 at 19:47 Comment(0)
P
0

Selects an option by its value. Works also using an array of values. Find complete details http://davidstutz.github.io/bootstrap-multiselect/#methods

$('#example-select').multiselect('select', ['1', '2', '4']); 
Palatalized answered 25/12, 2020 at 7:58 Comment(0)
S
-3

You can try this:

$( "#data" ).val([ "100", "101" ]);
Sporule answered 26/11, 2016 at 8:7 Comment(1)
That is correct, but this clearly looks like you copied Yatin's answer.Revivify

© 2022 - 2024 — McMap. All rights reserved.