Javascript – Select2 multi select blank option always selected

javascriptjquery-select2

I am using select2 for multi select and when I select first time , any option , null value from blank option always get selected.
And another problem if I don't use placeholder first option get selected when loaded.

Here is my code for html(it includes some php):

<select class="form-control select2-multiple" name="category_id">
        <option></option>
        @foreach($instrument_category as $key=>$value)
            <option value="{{ $value }}">{{ $value }}</option>
        @endforeach
</select>

here is my jquery:

$(".select2-multiple").select2({
    'placeholder' : "Select Category",
    'multiple' : true,
    'defaultView': 'dropdown'
});

Again problem : blank value get selected when selected for first time.

Screenshot given.

blank value selected

Best Answer

I had the exact same issue. To resolve it: - add the multiple attribute to your select (multiple="multiple") - remove the empty option tag

In my case, I create the dropdowns dynamically. So I wrote this code to fix it.

            $('#' + selectorId).attr('multiple', 'multiple');
            $("#" + selectorId + " option")[0].remove();

            $("#" + selectorId).select2({
                multiple: true,
                width: '100%',
                placeholder: "-- Select --"
            });