JQuery select2 set default value from an option in

2019-01-13 04:26发布

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

10条回答
forever°为你锁心
2楼-- · 2019-01-13 04:58

If you are using an array data source you can do something like below -

$(".select").select2({
    data: data_names
});
data_names.forEach(function(name) {
    if (name.selected) {
        $(".select").select2('val', name.id);
    }
});

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.

查看更多
Rolldiameter
3楼-- · 2019-01-13 05:02

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

查看更多
仙女界的扛把子
4楼-- · 2019-01-13 05:02

The above solutions did not work for me, but this code from Select2's own website did:

$('select').val('US'); // Select the option with a value of 'US'
$('select').trigger('change'); // Notify any JS components that the value changed

Webpage found here

Hope this helps for anyone who is struggling, like I was.

查看更多
爷、活的狠高调
5楼-- · 2019-01-13 05:04
    $('select').select2("val",null);
查看更多
登录 后发表回答