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

当前回答

要重置表单,有些人会有一个重置按钮。 在脚本标记中添加以下代码

$('.your_btn_class').click(function(){
    $('#select_field_id').val([]);
    $("#select_field_id").select2({
    placeholder: "this is a placeholder",
    });
});

或者清空选择字段而不保留占位符:

$('.your_btn_class').click(function(){
    $('#select_field_id').val([]);
 });

其他回答

公认的答案不适用于我的情况。我正在尝试,而且很有效:

定义select2:

$("#customers_select").select2({
    placeholder: "Select a State",
    allowClear: true
});

or

$("#customers_select").select2({
    placeholder: "Select a State"
});

重置:

$("#customers_select").val('').trigger('change')

or

$("#customers_select").empty().trigger('change')

对于占位者

$("#stateID").select2({
    placeholder: "Select a State"
});

重置一个选择2

$('#stateID').val('');
$('#stateID').trigger('change');

希望这能有所帮助

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

这将再次显示占位符。

一个[非常]俗气的方法(我看到它适用于4.0.3版本):

var selection = $("#DelegateId").data("select2").selection;
var evt = document.createEvent("UIEvents");
selection._handleClear(evt);
selection.trigger("toggle", {});

allowClear必须设置为true select元素中必须存在空选项

删除所选值

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

清除选项值

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