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

当前回答

在尝试了这里的前10个解决方案并失败后,我发现这个解决方案是有效的(参见“nilov评论于4月7日•编辑”):

(function ($) {
   $.fn.refreshDataSelect2 = function (data) {
       this.select2('data', data);

       // Update options
       var $select = $(this[0]);
       var options = data.map(function(item) {
           return '<option value="' + item.id + '">' + item.text + '</option>';
       });
       $select.html(options.join('')).change();
   };
})(jQuery);

然后进行更改:

var data = [{ id: 1, text: 'some value' }];
$('.js-some-field').refreshDataSelect2(data);

(作者最初显示var $select = $(this[1]);,评论者更正为var $select = $(this[0]);,这是我上面显示的。)

其他回答

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

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

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

删除所选值

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

清除选项值

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

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

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

必须将select2定义为

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

重置select2

$("#customers_select").select2("val", "");
$('myselectdropdown').select2('val', '0')

0是下拉列表的第一个值