select2 为空后占位符不显示
Placeholder does not show after select2 empty
select2为空后不显示占位符
我的 select2 已初始化,当我加载模态时,我必须删除值,才能加载新值。但是当我这样做时,一旦加载了值,占位符就不会显示。
密码是:
<select class="mySelect2" name="state" data-width="100%" data-placeholder="{% trans "New state" %}">
<option></option>
</select>
let mySelect2 = $('select.mySelect2');
// 在打开模态...
let options = $.map(data, (obj) => {
return {'id': obj.uuid, 'text': obj.name, 'data-required-text': obj['text_required']}
});
mySelect2.empty();
mySelect2.select2({
data: options,
});
我尝试了不同的方法,但都不起作用。它总是显示第一个选项。
也许我做错了什么,我该怎么办?我需要保留占位符并在更改时获取选项。
示例:https://codesandbox.io/s/morning-bird-y8h6r?file=/index.html
非常感谢。
当您调用 .empty()
时,您将删除所有子节点,包括空白选项。
The documentation 关于占位符的说法:
For single selects only, in order for the placeholder value to appear, you must have a blank as the first option in your control.
尝试删除除第一个选项之外的所有选项:
mySelect2.find("option:not(:first-child)").remove();
select2为空后不显示占位符
我的 select2 已初始化,当我加载模态时,我必须删除值,才能加载新值。但是当我这样做时,一旦加载了值,占位符就不会显示。
密码是:
<select class="mySelect2" name="state" data-width="100%" data-placeholder="{% trans "New state" %}">
<option></option>
</select>
let mySelect2 = $('select.mySelect2');
// 在打开模态...
let options = $.map(data, (obj) => {
return {'id': obj.uuid, 'text': obj.name, 'data-required-text': obj['text_required']}
});
mySelect2.empty();
mySelect2.select2({
data: options,
});
我尝试了不同的方法,但都不起作用。它总是显示第一个选项。
也许我做错了什么,我该怎么办?我需要保留占位符并在更改时获取选项。
示例:https://codesandbox.io/s/morning-bird-y8h6r?file=/index.html
非常感谢。
当您调用 .empty()
时,您将删除所有子节点,包括空白选项。
The documentation 关于占位符的说法:
For single selects only, in order for the placeholder value to appear, you must have a blank as the first option in your control.
尝试删除除第一个选项之外的所有选项:
mySelect2.find("option:not(:first-child)").remove();