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

当前回答

我知道这是一个老问题,但这适用于select2 4.0版本

 $('#select2-element').val('').trigger('change');

or

$('#select2-element').val('').trigger('change.select2'); 

如果你有变化事件绑定到它

其他回答

必须将select2定义为

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

重置select2

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

Select2使用了一个特定的CSS类,所以重置它的简单方法是:

$('.select2-container').select2('val', '');

这样做的好处是,如果在同一个表单中有多个Select2,它们都会被这个命令重置。

不管什么时候

$('myselectdropdown').select2('val', '').trigger('change');

在三到四次触发后,我开始有一些延迟。我想是内存泄漏了。它不在我的代码中,因为如果我删除这行,我的应用程序是无延迟的。

因为我有allowClear选项设置为true,我去

$('.select2-selection__clear').trigger('mousedown');

后面可以跟着$('myselectdropdown').select2('close');事件触发器在select2 dom元素上如果你想关闭打开建议下拉列表。

一个[非常]俗气的方法(我看到它适用于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(“);