5

I am using select2 for Multiselect option in my form.In the form I am using key controls to traverse thru the form.So If I press tab key it should traverse thru the fields in the forms.When I press tab to go to select2 textbox,it opens the options with default selection of first item.When I press tab to move to another field,it automatically selected.I want to avoid this.Please help...

I want to avoid default first element selection in select2 plugin.I have tried remove highlight() function when calling select2.It is working but not able to select element.

    $("#" + elementID).select2({
        data: {results: itemArray, name: 'name'},
        formatSelection: format,
        formatResult: format,
        multiple: true,
        closeOnSelect: false,
        height: height,
        width: width,
        allowClear:true,
        initSelection: function (element, callback) {
            var data = [];
            $(element.val().split(",")).each(function () {
               data.push({id: this.toString(), name: this.toString()});
            });
           return callback(data);
        },
        createSearchChoice: function (term, data) {
            
            if ($(data).filter(function () {
                return this.name.localeCompare(term) === 0;
            }).length === 0) {
               return {id: term, name: term};
            }
    
        }

    }).select2('data', null).one('select2-focus', select2Focus).on("select2-blur", function () {
    $(this).one('select2-focus', select2Focus);
});
kohane15
  • 809
  • 12
  • 16
rekha s
  • 577
  • 5
  • 7
  • 24

3 Answers3

5

You might need to add the multiple attribute to the select itself

<select class="js-data-example-ajax" multiple="multiple">
...
</select>

Ref: https://github.com/select2/select2/issues/3878

Tincho825
  • 829
  • 1
  • 13
  • 15
3

Put this as a first option in your select, in HTML

<option value="" selected disabled>Select item...</option>
hocikto
  • 871
  • 1
  • 14
  • 29
1

Adding an empty option will fix the issue.

$(document).ready(function() {
   $('select').select2({
  placeholder: {
      id: '', // the value of the option
      text: 'None Selected'
    },
    allowClear: true
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<select style="width : 150px">
        <option value=""></option>
        <option value="AL">Alabama</option>
        <option value="NJ">New Jesrsey</option>
</select>
Jajikanth pydimarla
  • 1,512
  • 13
  • 11