twitter-bootstrap JQuery 为引导选择选择器设置预选值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25510796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery Setting preselected values for bootstrap select picker
提问by user2906420
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.
以上没有选择修道院和贝尔格雷夫的价值观。我能做什么。
回答by klasske
You could use JSON.parseto revert the string to an array, so:
您可以使用JSON.parse将字符串恢复为数组,因此:
$('#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));
回答by divya
response.user_accountsis an array, but it just shows the first value as a dropdown selection, not all values of the array. Please suggest
response.user_accounts是一个数组,但它只是将第一个值显示为下拉选择,而不是数组的所有值。请建议
if (response.user_accounts) {
$('#account').selectpicker('val', response.user_accounts.account_id);
}

