我如何设置占位符的值重置由select2。在我的例子中,如果位置或等级选择框被单击,我的select2有一个值,那么select2的值应该重置并显示默认占位符。这个脚本正在重置值,但不会显示占位符

$("#locations, #grade ").change(function() {
   $('#e6').select2('data', {
     placeholder: "Studiengang wählen",
     id: null,
     text: ''
   });
});

$("#e6").select2({
   placeholder: "Studiengang wählen",
   width: 'resolve',
   id: function(e) {
     return e.subject;
   },
   minimumInputLength: 2,
   ajax: {
     url: "index.php?option=com_unis&task=search.locator&tmpl=component&<?php echo JSession::getFormToken() ?>=1",
     dataType: 'json',
     data: function(term, page) {
       return {
         q: term, // search term
         g: $('#grade option:selected').val(),
         o: $('#locations option:selected').val()
       };
     },
     results: function(data, page) {
       return {
         results: data
       };
     }
   },
   formatResult: subjectFormatResult,
   formatSelection: subjectFormatSelection,
   dropdownCssClass: "bigdrop",
   escapeMarkup: function(m) {
     return m;
   }
});

当前回答

按照推荐的方法来做。在文档https://select2.github.io/options.html#my-first-option-is-being-displayed-instead-of-my-placeholder中找到(这似乎是一个相当常见的问题):

当这种情况发生时,通常意味着您在<select>中没有空白的<option></option>作为第一个选项。

如:

<select>
   <option></option>
   <option value="foo">your option 1</option>
   <option value="bar">your option 2</option>
   <option value="etc">...</option>
</select>

其他回答

必须将select2定义为

$("#customers_select").select2({
    placeholder: "Select a customer",
    initSelection: function(element, callback) {                   
    }
});

重置select2

$("#customers_select").select2("val", "");

在js文件中使用这段代码

$('#id').val('1');
$('#id').trigger('change');

我已经阅读了所有的答案,其中很多都不赞成。

这是当前清除和设置占位符值的方法:

// Clear and put a blank select placeholder
$("#MySelect").prop('disabled', false).find("option:gt(0)").remove();

我也有这个问题,它源于val(null).trigger("change");在占位符重置之前抛出No select2/compat/inputData错误。我通过捕捉错误并直接设置占位符(以及宽度)解决了这个问题。 注意:如果你有一个以上,你需要抓住每一个。

try{
    $("#sel_item_ID").select2().val(null).trigger("change");
}catch(err){
    console.debug(err)
}
try{
    $("#sel_location_ID").select2().val(null).trigger("change");
}catch(err){
    console.debug(err)
}
$('.select2-search__field')[0].placeholder='All Items';
$('.select2-search__field')[1].placeholder='All Locations';
$('.select2-search__field').width(173);

我正在运行Select2 4.0.3

如果你想在关闭一个模态时清除所有的select2输入,那么你可以添加一个类“select2”,并将它们都设置回它们的占位符,如下所示。

$('#myModal').on('hidden.bs.modal', function (e) {
    $(this)
        .find(".select2").select2({placeholder: "Choose an option"})
        .val('').trigger('change.select2');
});

这种一次性全部重置的方法也可以用于表单。 我使用的版本是4.0.10