jQuery select2 onchange 事件只工作一次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17731694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:51:09  来源:igfitidea点击:

select2 onchange event only works once

jqueryeventsonchangejquery-select2

提问by PartySoft

I have a problem with the jQuery's Select2.

我对 jQuery 的 Select2 有问题。

When the page loads, if O click on the search result it will select and trigger the event onchange, but only the first time.

当页面加载时,如果 O 点击搜索结果,它将选择并触发 onchange 事件,但仅限第一次。

If I search another time, it won't.

如果我再搜索一次,就不会了。

Here's my code (it's an Ajax based search):

这是我的代码(它是基于 Ajax 的搜索):

jQuery('#search_code').select2({
    'width': '600px',
    'tokenSeparators': [',', ' '],
    'closeOnSelect': false,
    'placeholder': 'scan or type a SKU or product or ESN',
    'minimumInputLength': 1,
    'ajax': {
        'url': 'lookProduct',
        'dataType': 'json',
        'type': 'POST',
        'data': function (term, page) {
            return {
                barcode: term,
                page_limit: 3,
                page: page
            };
        },
        'results': function (data, page) {
            return {
                results: data
            };
        }
    }
}).on('change', function (e) {
    var str = $("#s2id_search_code .select2-choice span").text();

    DOSelectAjaxProd(this.value, str);
    //this.value
}).on('select', function (e) {
    console.log("select");

});

回答by Steel Brain

This is what I am using:

这就是我正在使用的:

$("#search_code").live('change', function(){
  alert(this.value)
});

For latest jQuery users, this one should work:

对于最新的 jQuery 用户,这个应该可以工作:

$(document.body).on("change","#search_code",function(){
 alert(this.value);
});

回答by Nisarg

As of version 4.0.0, events such as select2-selecting, no longer work. They are renamed as follows:

版本 4.0.0 开始,诸如 , 之类的事件select2-selecting不再起作用。它们的重命名如下:

  • select2-close is now select2:close
  • select2-open is now select2:open
  • select2-opening is now select2:opening
  • select2-selecting is now select2:selecting
  • select2-removed is now select2:removed
  • select2-removing is now select2:unselecting
  • select2-close 现在是 select2:close
  • select2-open 现在是 select2:open
  • select2-opening 现在是 select2:opening
  • select2-selecting 现在是 select2:selecting
  • select2-removed 现在是 select2:removed
  • select2-removing 现在是 select2:unselecting

Ref: https://select2.org/programmatic-control/events

参考:https: //select2.org/programmatic-control/events

(function($){
  $('.select2').select2();
  
  $('.select2').on('select2:selecting', function(e) {
    console.log('Selecting: ' , e.params.args.data);
  });
})(jQuery);
body{
  font-family: sans-serif;
}

.select2{
  width: 100%;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>

<select class="select2" multiple="multiple">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
  <option value="5">Option 5</option>
  <option value="6">Option 6</option>
  <option value="7">Option 7</option>
</select>

回答by Keith Muenze

Apparently the change event is not fired if a selection already exists when using data. I ended up updating the data manually on select to resolve the problem.

显然,如果在使用数据时选择已经存在,则不会触发更改事件。我最终在选择时手动更新数据以解决问题。

$("#search_code").on("select2-selecting", function(e) {
    $("#search_code").select2("data",e.choice);
});

I know this is pretty late but hopefully this answer will save others time.

我知道这已经很晚了,但希望这个答案能节省其他人的时间。

回答by cpugourou

This is due because of the items id being the same. On change fires only if a different item id is detected on select.

这是因为项目 ID 相同。只有在选择时检测到不同的项目 ID 时才会触发更改。

So you have 2 options: First is to make sure that each items have a unique id when retrieving datas from ajax.

所以你有两个选择:首先是确保每个项目在从 ajax 检索数据时都有一个唯一的 id。

Second is to trigger a rand number at formatSelection for the selected item.

其次是在 formatSelection 为所选项目触发一个随机数。

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

.

.

formatSelection: function(item) {item.id =getRandomInt(1,200)}

回答by HamidReza

$('#search_code').select2({
.
.
.
.
}).on("change", function (e) {
      var str = $("#s2id_search_code .select2-choice span").text();
      DOSelectAjaxProd(e.val, str);
});

回答by Dradge

Set your .onlistener to check for specific select2 events. The "change" event is the same as usual but the others are specific to the select2 control thus:

设置您的.on侦听器以检查特定的 select2 事件。"change" 事件与往常一样,但其他事件特定于 select2 控件,因此:

  • change
  • select2-opening
  • select2-open
  • select2-close
  • select2-highlight
  • select2-selecting
  • select2-removed
  • select2-loaded
  • select2-focus
  • 改变
  • select2-开
  • 选择2-打开
  • select2-关闭
  • select2-突出显示
  • select2-选择
  • select2-删除
  • select2-加载
  • select2-焦点

The names are self-explanatory. For example, select2-focusfires when you give focus to the control.

这些名称是不言自明的。例如,select2-focus当您将焦点放在控件上时触发。

回答by Stephane

My select2 element was not firing the onchangeevent as the drop down list offered only one value, making it impossible to change the value.

我的 select2 元素没有触发onchange事件,因为下拉列表只提供一个值,因此无法更改该值。

The value not having changed, no event was fired and the handler could not execute.

值没有改变,没有事件被触发,处理程序无法执行。

I then added another handler to clear the value, with the select2-openhandler being executed before the onchangehandler.

然后我添加了另一个处理程序来清除该值,select2-open处理程序在onchange处理程序之前执行。

The source code now looks like:

源代码现在看起来像:

el.on("select2-open", function(e) {
    $(this).val('');
});
el.on('change', function() {
    ...
});

The first handler clears the value, allowing the second handler to fire up even if selecting the same value.

第一个处理程序清除该值,即使选择相同的值,也允许第二个处理程序启动。