简体   繁体   中英

Placeholder does not show after select2 empty

The placeholder is not displayed after select2 empty.

My select2 is initialized and when I load a modal, I have to delete the values, to load new ones. But when I do this, the placeholder is not displayed once the values are loaded.

The code is:

<select class="mySelect2" name="state" data-width="100%" data-placeholder="{% trans "New state" %}">
   <option></option>
</select>
let mySelect2 = $('select.mySelect2');

// On open modal...

 let options = $.map(data, (obj) => {
            return {'id': obj.uuid, 'text': obj.name, 'data-required-text': obj['text_required']}
   });
  mySelect2.empty();
   mySelect2.select2({
                data: options,
            });

I have tried different ways but they don't work. It always shows me the first option.

Maybe I do something wrong, what can I do? I need to keep the placeholder and get the option when it changes.

Example: https://codesandbox.io/s/morning-bird-y8h6r?file=/index.html

Thank you so much.

When you call .empty() you are removing all the child nodes, including the blank option.

The documentation says this about placeholders:

For single selects only, in order for the placeholder value to appear, you must have a blank as the first option in your control.

Try removing all the options except the first one:

mySelect2.find("option:not(:first-child)").remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM