简体   繁体   English

占位符在 select2 为空后不显示

[英]Placeholder does not show after select2 empty

The placeholder is not displayed after select2 empty. select2 为空后不显示占位符。

My select2 is initialized and when I load a modal, I have to delete the values, to load new ones.我的 select2 已初始化,当我加载模式时,我必须删除值以加载新值。 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示例: 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.当您调用.empty()时,您将删除所有子节点,包括空白选项。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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