我如何设置占位符的值重置由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 3.2版本,这为我工作:

$('#select2').select2("data", "");

不需要实现initSelection

其他回答

我在这个案例中是这样做的:

  $('#select').val('');
  $('.select2.select2-container').remove();
  $('.select2').select2();

我将选择值更改为空 我删除了select2的容器 Re-call select2

我知道这是一个老问题,但这适用于select2 4.0版本

 $('#select2-element').val('').trigger('change');

or

$('#select2-element').val('').trigger('change.select2'); 

如果你有变化事件绑定到它

按照推荐的方法来做。在文档https://select2.github.io/options.html#my-first-option-is-being-displayed-instead-of-my-placeholder中找到(这似乎是一个相当常见的问题):

当这种情况发生时,通常意味着您在<select>中没有空白的<option></option>作为第一个选项。

如:

<select>
   <option></option>
   <option value="foo">your option 1</option>
   <option value="bar">your option 2</option>
   <option value="etc">...</option>
</select>

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

$('.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 customer",
    initSelection: function(element, callback) {                   
    }
});

重置select2

$("#customers_select").select2("val", "");