JQuery select2 set default value from an option in list?

前端 未结 10 768
傲寒
傲寒 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:39

    One way to accomplish this is...

    $('select').select2().select2('val', $('.select2 option:eq(1)').val());
    

    So basically you first initalize the plugin then specify the default value using the 'val' parameter. The actual value is taken from the specified option, in this case #1. So the selected value from this example would be "bar".

    
    

    Hope this is useful to someone else.

提交回复
热议问题