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

当前回答

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

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

其他回答

不管什么时候

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

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

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

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

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

我已经尝试了上述解决方案,但没有一个适用于版本4x。

我想要实现的是:清除所有选项,但不要触摸占位符。这个代码适用于我。

selector.find('option:not(:first)').remove().trigger('change');

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

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

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

在js文件中使用这段代码

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