JQuery select2 set default value from an option in list?

前端 未结 10 745
傲寒
傲寒 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".

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

    Hope this is useful to someone else.

    0 讨论(0)
  • 2020-12-04 13:41

    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.

    0 讨论(0)
  • 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

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

    0 讨论(0)
  • 2020-12-04 13: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
    
    0 讨论(0)
提交回复
热议问题