JQuery select2从列表中的选项设置默认值? [英] JQuery select2 set default value from an option in list?

查看:2779
本文介绍了JQuery select2从列表中的选项设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用JQuery Select2插件设置select元素的默认/选定值。

解决方案

还有一种方法 - 只需将 selected =selected属性添加到 select 标记并调用 select2 就可以了。它必须采用您选择的值。无需额外的JavaScript。像这样:



加价

  < select class =select2> 
< option id =foo> Some Text< / option>
< option id =barselected =selected>其他文字< /选项>
< / select>

JavaScript



< 。pre> $( '选择')SELECT2(); //哦,就是这个!

请参阅小提琴: http://jsfiddle.net/6hZFU/



编辑:(谢谢,Jay Haase!)



如果这不起作用,请尝试设置 val 属性select2 null ,清除值,如下所示:

  $('select')。select2(val,null); //一个小点多一点:) 

在此之后,设置<$ c很简单$ c> val 到无论你想要什么


I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.

解决方案

One more way - just add a selected = "selected" attribute to the select markup and call select2 on it. It must take your selected value. No need for extra JavaScript. Like this :

Markup

<select class="select2">
   <option id="foo">Some Text</option>
   <option id="bar" selected="selected">Other Text</option>
</select>

JavaScript

$('select').select2(); //oh yes just this!

See fiddle : http://jsfiddle.net/6hZFU/

Edit: (Thanks, Jay Haase!)

If this doesn't work, try setting the val property of select2 to null, to clear the value, like this:

$('select').select2("val", null); //a lil' bit more :)

After this, it is simple enough to set val to "Whatever You Want".

这篇关于JQuery select2从列表中的选项设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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