I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
If you are using an array data source you can do something like below -
This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.
One more way - just add a
selected = "selected"
attribute to theselect
markup and callselect2
on it. It must take your selected value. No need for extra JavaScript. Like this :Markup
JavaScript
See fiddle : http://jsfiddle.net/6hZFU/
Edit: (Thanks, Jay Haase!)
If this doesn't work, try setting the
val
property ofselect2
tonull
, to clear the value, like this:After this, it is simple enough to set
val
to"Whatever You Want"
.The above solutions did not work for me, but this code from Select2's own website did:
Webpage found here
Hope this helps for anyone who is struggling, like I was.