我如何设置占位符的值重置由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;
   }
});

当前回答

一个[非常]俗气的方法(我看到它适用于4.0.3版本):

var selection = $("#DelegateId").data("select2").selection;
var evt = document.createEvent("UIEvents");
selection._handleClear(evt);
selection.trigger("toggle", {});

allowClear必须设置为true select元素中必须存在空选项

其他回答

我也有这个问题,它源于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

    $('#selectelementid').select2({
        placeholder: "Please select an agent",
        allowClear: true // This is for clear get the clear button if wanted 
    });

以及以编程方式清除选择输入

    $("#selectelementid").val("").trigger("change");
    $("#selectelementid").trigger("change");

这个解决方案为我工作(Select2 4.0.13)

$('#select').on("select2:unselecting", function (e) {
   $(this).val('').trigger('change');
   e.preventDefault();
});

必须将select2定义为

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

重置select2

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

一个[非常]俗气的方法(我看到它适用于4.0.3版本):

var selection = $("#DelegateId").data("select2").selection;
var evt = document.createEvent("UIEvents");
selection._handleClear(evt);
selection.trigger("toggle", {});

allowClear必须设置为true select元素中必须存在空选项