todc / todc-select2

Google-themed fork of Select2. Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.
http://todc.github.com/todc-select2/
Other
112 stars 17 forks source link

How to pre-select an option? #2

Closed larryzhao closed 11 years ago

larryzhao commented 11 years ago

Hi, Tim,

Great work! Thanks. My scenario is the first example, I have a simple select and I use .select2() to turn it. But how could I pre-select like Alaska in the the first example?

I tag the option as selected=selected but it just doesn't work.

todc commented 11 years ago

Adding the "selected" attribute to an

http://jsfiddle.net/PTfYG/1/

Can you provide a jsfiddle to your example that doesn't work?

larryzhao commented 11 years ago

Hi, Tim,

I figured it out. Actually my option is dynamically inserted, so it doesn't work unless I call select2() after the options are all prepared. Here's the fiddle http://jsfiddle.net/larryzhao/FSuFt/

Thanks for the help.

todc commented 11 years ago

Glad you figured it out.

You may also be interested in the "Reacting to external value changes" section of the docs:

http://todc.github.com/todc-select2/#event_ext_change

I think it addresses your specific situation. For example, here's an update to your jsfiddle where I call select2() before adding the options (which will render the empty select menu). Triggering the "change" event after dynamically adding the new option elements will re-render the select2 menu and choose the selected value appropriately.

http://jsfiddle.net/FSuFt/13/