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条回答
放我归山
2楼-- · 2019-01-13 04:38

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

<select class=".select2">
  <option id="foo">Some Text</option>
  <option id="bar">Other Text</option>
</select>

Hope this is useful to someone else.

查看更多
闹够了就滚
3楼-- · 2019-01-13 04:38

Don't know others issue, Only this code worked for me.

$('select').val('').select2();
查看更多
混吃等死
4楼-- · 2019-01-13 04:41

For 4.x version

$('#select2Id').val(__INDEX__).trigger('change');

to select value with INDEX

$('#select2Id').val('').trigger('change');

to select nothing (show placeholder if it is)

查看更多
Explosion°爆炸
5楼-- · 2019-01-13 04:44
$("#id").select2("val", null); //this will not work..you can try

You should actually do this...intialise and then set the value..well this is also the way it worked for me.

$("#id").select2().select2("val", null);
$("#id").select2().select2("val", 'oneofthevaluehere');
查看更多
Anthone
6楼-- · 2019-01-13 04:45

For ajax select2 multiple select dropdown i did like this;

  //preset element values
  //topics is an array of format [{"id":"","text":""}, .....]
        $(id).val(topics);
          setTimeout(function(){
           ajaxTopicDropdown(id,
                2,location.origin+"/api for gettings topics/",
                "Pick a topic", true, 5);                      
            },1);
        // ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url
查看更多
Bombasti
7楼-- · 2019-01-13 04:53

How is this?

Markup

<select>
   <option value="foo">Some Text</option>
   <option value="bar">Other Text</option>
</select>

JavaScript

$('select').val('bar').select2();
查看更多
登录 后发表回答