我使用的Bootstrap-Select插件如下所示:
HTML
<select name="selValue" class="selectpicker">
<option value="1">Val 1</option>
<option value="2">Val 2</option>
<option value="3">Val 3</option>
<option value="4">Val 4</option>
</select>
Javascript
$('select[name=selValue]').selectpicker();
现在,我想要将选择的值设置为单击按钮时选择...如下所示:
$('#mybutton').click(function(){
$('select[name=selValue]').val(1);
});
但是什么也没发生。
我如何才能做到这一点?
发布于 2013-02-11 08:53:27
值是正确选择的,但是你没有看到它,因为插件隐藏了真正的选择,并显示了一个带有无序列表的按钮,所以,如果你想让用户看到选择上的选定值,你可以这样做:
//Get the text using the value of select
var text = $("select[name=selValue] option[value='1']").text();
//We need to show the text inside the span that the plugin show
$('.bootstrap-select .filter-option').text(text);
//Check the selected attribute for the real select
$('select[name=selValue]').val(1);
编辑:
就像@blushrt指出的那样,更好的解决方案是:
$('select[name=selValue]').val(1);
$('.selectpicker').selectpicker('refresh')
编辑2:
要选择多个值,请将这些值作为数组传递。
发布于 2013-12-04 23:45:32
$('select[name=selValue]').val(1);
$('.selectpicker').selectpicker('refresh');
这就是您需要做的全部工作。不需要直接更改selectpicker生成的html,只需更改隐藏的选择字段,然后调用selectpicker('refresh')。
发布于 2015-10-13 06:35:18
$('.selectpicker').selectpicker('val', YOUR_VALUE);
https://stackoverflow.com/questions/14804253
复制相似问题