我如何设置占位符的值重置由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使用了一个特定的CSS类,所以重置它的简单方法是:

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

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

其他回答

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

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

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

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

我不知道是否有人经历过这种情况,但一旦代码命中触发器('change'),我的javascript就停止了,从未从触发器返回,其余的函数从未执行。

我对jquery触发器不够熟悉,不能说这是预期的。我通过将它包装在setTimeout中来解决它,这很难看,但很有效。

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

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

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

使用以下命令配置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");
<label for="RECEIVED_BY" class="control-label"> Received into store By </label>
<label class="pull-right">
  <button
    type="button"
    title="Clear Received into store By"
    class="receive_clear clear-button"
    aria-label="Select2 options"
  >
    x
  </button></label
>
<select type="text" class="clear_receive_info_by">
  <option value="">--Select--</option>
  <option value="value1">value1</option>
  <option value="value2">value2</option>
  <option value="value3">value3</option>
</select>

jQuery:

var $clear_receive_info_by = $(".clear_receive_info_by").select2();
$(".receive_clear").on("click", function () {
    $clear_receive_info_by.val(null).trigger("change");
});