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

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

问题描述

我正在使用 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);
});

但是什么也没发生.

我该如何实现?

推荐答案

该值已正确选择,但您没有看到它,因为该插件隐藏了真正的select并显示具有无序列表的按钮,因此,如果您希望用户在选择项上看到所选的值,您可以执行以下操作:

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

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

Edit 2:

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

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

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