user2906420
user2906420

Reputation: 1269

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.

Upvotes: 1

Views: 11691

Answers (2)

divya
divya

Reputation: 1

response.user_accounts is an array, but it just shows the first value as a dropdown selection, not all values of the array. Please suggest

if (response.user_accounts) {
          $('#account').selectpicker('val', response.user_accounts.account_id);
        }

Upvotes: 0

klasske
klasske

Reputation: 2184

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));

Upvotes: 6

Related Questions