我如何设置占位符的值重置由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改变了API:

Select2: Select2 ("val")方法已弃用 并将在以后的Select2版本中删除。使用$element.val()代替。

现在最好的方法是:

$('#your_select_input').val('');

编辑:2016年12月意见表明,以下是更新的方式:

$('#your_select_input').val([]);

其他回答

必须将select2定义为

$("#customers_select").select2({
    placeholder: "Select a customer",
    initSelection: function(element, callback) {                   
    }
});

重置select2

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

我已经尝试了上述解决方案,但没有一个适用于版本4x。

我想要实现的是:清除所有选项,但不要触摸占位符。这个代码适用于我。

selector.find('option:not(:first)').remove().trigger('change');

对于占位者

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

重置一个选择2

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

希望这能有所帮助

为了重置值和占位符,我只需要重新初始化select2元素:

$( "#select2element" ).select2({
    placeholder: '---placeholder---',
    allowClear: true,
    minimumResultsForSearch: 5,
    width:'100%'
});

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

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

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

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