Select2 multi select blank option always selected
Asked Answered
S

2

11

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

Stanwinn answered 20/4, 2018 at 13:59 Comment(2)
in select2 Docs it says: "For multi-selects, you must not have an empty <option> element:"Helmer
If I remove empty option it selects the first option and place holder is also not shown, then.Stanwinn
S
14

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 --"
            });
Scupper answered 12/9, 2018 at 14:26 Comment(0)
P
11

As it's stated in Select2 Documentation https://select2.org/placeholders :

For multi-selects, you must not have an empty element

This leads to the problem that the browser selects the first option of "select" by default, so as a workaround there is a hacky way that worked for me

Either use this :

$your_select_element.select2({
    multiple: true,
    placeholder: "Select whatever..."
});
// set the value to null or empty string '', then trigger (change) event
$your_select_element.val(null).trigger("change");

or this :

// the initial call of select2
$your_select_element.select2({
    multiple: true,
    placeholder: "Select whatever..."
});
$your_select_element.val(null);
$('.select2.select2-container').remove();
//re-call select2 on your element 
$your_select_element.select2({
    multiple: true,
    placeholder: "Select whatever..."
});

It's no-brainer that the first way is the way to go ;) Hope this helps someone

Pard answered 21/2, 2019 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.