Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Default selection in Select2 Jquery Plugin

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);
});
like image 845
rekha s Avatar asked Sep 04 '26 21:09

rekha s


2 Answers

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

like image 159
Tincho825 Avatar answered Sep 07 '26 15:09

Tincho825


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

<option value="" selected disabled>Select item...</option>
like image 41
hocikto Avatar answered Sep 07 '26 13:09

hocikto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!