Search code examples
jquery-select2dropdown

Displaying first 5 options as default in select2


I am trying to display the first 5 options as default in rendering select2.

Select countries
____________

America
Canada
England
France
Spain

I made it multiple and used selected, so it could display but not as straightforward like the above.

How can I set it up like this?

I used the open option, so it displays them like above.

$('#id').select2('open')

However, when I click on anywhere on the screen, it closes. How can I keep it open all the time?


Solution

  • Lets say that your Dropdown HTML is like below:

    <select multiple="multiple" id="s1" style="width: 300px">
            <option value="1">America</option>
            <option value="2">Canada</option>
            <option value="3">England</option>
            <option value="4">France</option>
            <option value="5">Spain</option>
    </select>
    
    
    

    If you want to always keep Open the dropdown, you can use following code. This prevents the closing by overriding the callback method.

    $(doucment).ready(function() {
    var list = $('#s1').select2({
      closeOnSelect: false,
    }).on("select2:closing", function(e) {
      e.preventDefault();
    }).on("select2:closed", function(e) {
      list.select2("open");
    });
    
    
    list.select2("open");
    });
    
    

    Please see the working JSFiddle