如何使用 bootstrap 中的 selectpicker 插件在选择时设置选定的值 [英] How to set selected value on select using selectpicker plugin from bootstrap

查看:21
本文介绍了如何使用 bootstrap 中的 selectpicker 插件在选择时设置选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Bootstrap-Select 插件,如下所示:

I'm using the Bootstrap-Select plugin like this:

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

现在我想将选择的值设置为单击按钮时的这个选择......像这样:

Now I want to set the value selected to this select when button clicked... something like this:

$('#mybutton').click(function(){
   $('select[name=selValue]').val(1);
});

但什么也没发生.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

值被正确选择,但是你没有看到它,因为插件隐藏了真正的选择并显示了一个带有无序列表的按钮,所以,如果你希望用户在选择上看到选定的值,您可以执行以下操作:

The value is correctly selected, but you didn't see it because the plugin hide the real select and show a button with an unordered list, so, if you want that the user see the selected value on the select you can do something like this:

//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 指出的那样,更好的解决方案是:

Like @blushrt points out, a better solution is:

$('select[name=selValue]').val(1);
$('.selectpicker').selectpicker('refresh')

编辑 2:

要选择多个值,请将值作为数组传递.

Edit 2:

To select multiple values, pass the values as an array.

这篇关于如何使用 bootstrap 中的 selectpicker 插件在选择时设置选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆