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

当前回答

唯一对我有用的是:

$('select2element').val(null).trigger("change")

我使用的是4.0.3版本

参考

根据Select2文档

其他回答

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

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

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

我使用select2版本select2 4.0.5 $ (' .classToClear ') .select2 () .val(“);

公认的答案不适用于我的情况。我正在尝试,而且很有效:

定义select2:

$("#customers_select").select2({
    placeholder: "Select a State",
    allowClear: true
});

or

$("#customers_select").select2({
    placeholder: "Select a State"
});

重置:

$("#customers_select").val('').trigger('change')

or

$("#customers_select").empty().trigger('change')

使用以下命令配置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");

对于加载远程数据的用户,这将在不触发ajax的情况下将select2重置为占位符。适用于v4.0.3:

$("#lstProducts").val("").trigger("change.select2");