JQuery select2 set default value from an option in list?

前端 未结 10 766
傲寒
傲寒 2020-12-04 13:07

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

10条回答
  •  失恋的感觉
    2020-12-04 13:44

    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

    
    

    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".

提交回复
热议问题