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

当前回答

用这个:

$('.select').val([]).trigger('change');

其他回答

我尝试了上面的解决方案,但对我不起作用。

这是一种hack,你不需要触发更改。

$("select").select2('destroy').val("").select2();

or

$("select").each(function () { //added a each loop here
        $(this).select2('destroy').val("").select2();
});

删除所选值

$('#employee_id').select2('val','');

清除选项值

$('#employee_id').html('');

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

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

首先,你必须像这样定义select2:

$('#id').select2({
    placeholder: "Select groups...",
    allowClear: true,
    width: '100%',
})

要重置select2,你可以简单地使用以下代码块:

$("#id > option").removeAttr("selected");
$("#id").trigger("change");

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

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

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