Search code examples
javascriptjquerytwitter-bootstrapbootstrap-select

JQuery Setting preselected values for bootstrap select picker


I want to pre-select multiple values from the below dropdown select. For this example i want to select 'Abbey' & 'Belgrave'

<select id="dropdown" multiple>
    <option value='Belgrave'>Belgrave</option>
    <option value='Abbey'>Abbey</option>
    <option value='Castle'>Castle</option>
</select> 

I can achieve this manually which works fine like this:

$('#dropdown').selectpicker('val', ['Abbey', 'Belgrave']);

The problem is by passing the array in string it does not work:

var wards = dsFilterOptions.Wards.split(",");
var strWard = "[";
for (i = 0; i < wards.length; i++) {
    strWard += "'" + wards[i] + "',";
}
strWard = strWard.slice(0, -1); //remove last comma
strWard += "]";
$('#dropdown').selectpicker('val', strWard);

The above does not select the Abbey & Belgrave values.What i can do.


Solution

  • You could use JSON.parse to revert the string to an array, so:

    $('#dropdown').selectpicker('val', JSON.parse(strWard));
    

    Edit, with single quotes fixed:

    var wards = dsFilterOptions.Wards.split(",");
    var strWard = '[';
    for (i = 0; i < wards.length; i++) {
        strWard += '"' + wards[i] + '",';
    }
    strWard = strWard.slice(0, -1); //remove last comma
    strWard += ']';
    $('#dropdown').selectpicker('val', JSON.parse(strWard));