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

当前回答

我已经阅读了所有的答案,其中很多都不赞成。

这是当前清除和设置占位符值的方法:

// Clear and put a blank select placeholder
$("#MySelect").prop('disabled', false).find("option:gt(0)").remove();

其他回答

这是最新的select 2 api的工作片段。

重置或清除select2输入。

$("#selector").val([]).trigger('change');

i.e.

$( ".reset" ).on('click',function(){
    $(".select2input").val([]).trigger('change');
});

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

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

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

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

与Select2版本4.0.9这适用于我:

$( "#myselect2" ).val('').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");

在使用此$("#customers_select")清除该值之前。select2(“val”,“”); 尝试将焦点设置为重置单击的任何其他控件。

这将再次显示占位符。