jcv*_*gan 90 jquery twitter-bootstrap bootstrap-select
我正在使用这样的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>
Run Code Online (Sandbox Code Playgroud)
Javascript:
$('select[name=selValue]').selectpicker();
Run Code Online (Sandbox Code Playgroud)
现在我想在点击按钮时将选择的值设置为此选择...如下所示:
$('#mybutton').click(function(){
$('select[name=selValue]').val(1);
});
Run Code Online (Sandbox Code Playgroud)
但没有任何反应.
我怎样才能做到这一点?
Tom*_*duy 131
该值已正确选择,但您没有看到它,因为插件隐藏了真正的选择并显示了带有无序列表的按钮,因此,如果您希望用户在选择中看到所选值,您可以执行类似这样的操作:
//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);
Run Code Online (Sandbox Code Playgroud)
就像@blushrt指出的那样,更好的解决方案是:
$('select[name=selValue]').val(1);
$('.selectpicker').selectpicker('refresh')
Run Code Online (Sandbox Code Playgroud)
要选择多个值,请将值作为数组传递.
blu*_*hrt 63
$('select[name=selValue]').val(1);
$('.selectpicker').selectpicker('refresh');
Run Code Online (Sandbox Code Playgroud)
这就是你需要做的.无需直接更改生成的selectpicker html,只需更改隐藏的选择字段,然后调用selectpicker('refresh').
ced*_*lof 14
如果"val"参数用于设置值,则无需刷新,请参阅小提琴.使用括号作为值以启用多个选定值.
$('.selectpicker').selectpicker('val', [1]);
Run Code Online (Sandbox Code Playgroud)
Jan*_*ana 10
$('#mybutton').click(function(){
$('select[name=selValue]').val(1);
$('select[name=selValue]').change();
});
Run Code Online (Sandbox Code Playgroud)
这对我有用.
小智 8
实际上您的值已设置,但您的selectpicker未刷新
正如您可以从文档https://silviomoreto.github.io/bootstrap-select/methods/#selectpickerval中读到的那样
这样做的正确方法是
$('.selectpicker').selectpicker('val', 1);
Run Code Online (Sandbox Code Playgroud)
对于多个值,您可以添加值数组
$('.selectpicker').selectpicker('val', [1 , 2]);
Run Code Online (Sandbox Code Playgroud)
您可以通过调用元素上的 val 方法来设置选定的值。
$('.selectpicker').selectpicker('val', 'Mustard');
$('.selectpicker').selectpicker('val', ['Mustard','Relish']);
Run Code Online (Sandbox Code Playgroud)
这将选择多选中的所有项目。
$('.selectpicker').selectpicker('selectAll');
Run Code Online (Sandbox Code Playgroud)
详细信息可在现场获得:https : //silviomoreto.github.io/bootstrap-select/methods/
小智 5
$('selector').selectpicker('val',value);
代替选择器,您可以为选择器提供 class 或 id 例如: $('#mySelect').selectpicker('val',your_value)
| 归档时间: |
|
| 查看次数: |
239444 次 |
| 最近记录: |