我使用的是Oleg的select2 demo,但我想知道是否可以更改下拉菜单中当前选定的值.
例如,如果加载的四个值是:"Any", "Fruit", "Vegetable", "Meat"
,下拉列表默认为"Any"
,那么在JqGrid事件loadComplete
中,我如何将其更改为"Fruit"
?
Is this possible?
我使用的是Oleg的select2 demo,但我想知道是否可以更改下拉菜单中当前选定的值.
例如,如果加载的四个值是:"Any", "Fruit", "Vegetable", "Meat"
,下拉列表默认为"Any"
,那么在JqGrid事件loadComplete
中,我如何将其更改为"Fruit"
?
Is this possible?
For select2 version >= 4.0.0
其他解决方案可能不起作用,但是下面的例子应该起作用.
$('select').val('1').trigger('change');
$('select').val('1').trigger('change.select2');
请参阅此jsfiddle以了解这些示例.感谢@minlare提供的解决方案2.
Say I have a best friend select with people's names. So Bob, Bill and John (in this example I assume the Value is the same as the name). First I initialize select2 on my select:
$('#my-best-friend').select2();
Now I manually select Bob in the browser. Next Bob does something naughty and I don't like him anymore. So the system unselects Bob for me:
$('#my-best-friend').val('').trigger('change');
或者假设我让系统 Select 列表中的下一个,而不是Bob:
// I have assume you can write code to select the next guy in the list
$('#my-best-friend').val('Bill').trigger('change');
Select 2网站(参见Deprecated and removed methods)上可能对其他人有用的注释:
.select2('val')
你应该直接打电话.而不是在基础元素上.如果需要第二个参数(triggerChange),还应该调用.在元素上触发("更改").
$('select').val('1').trigger('change'); // instead of $('select').select2('val', '1');