最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - select2 'change' event doesn't trigger for the first time - Stack Overflow

programmeradmin3浏览0评论

I have Select2 Javascript widget on my page.

$('#order_address_select').select2({
  placeholder: "Select adress",
  ajax: {
    url: '<?=Yii::app()->getBaseUrl(true)?>/order/getplacemarklist',
    dataType: 'json',
  },
  tags: true,
});

When I'm typing some text, and if it is not found in database and not loaded through ajax, I can anyway choose it, cause attribute tags is setted to true. Then I have following code

 $('#order_address_select').change(function () {
   alert($("#order_address_select option[data-select2-tag='true']").val());
 });

The problem is when I'm typing text, and selecting it as a tag, event doesnt trigger for the first time. But when I'm typing text again, and selecting it, code alerts value of previously selected option. For example: I'm typing "aaa", selecting it, nothing happens, then I'm typing "bbb", selecting it, and got alert with "aaa"

I have Select2 Javascript widget on my page.

$('#order_address_select').select2({
  placeholder: "Select adress",
  ajax: {
    url: '<?=Yii::app()->getBaseUrl(true)?>/order/getplacemarklist',
    dataType: 'json',
  },
  tags: true,
});

When I'm typing some text, and if it is not found in database and not loaded through ajax, I can anyway choose it, cause attribute tags is setted to true. Then I have following code

 $('#order_address_select').change(function () {
   alert($("#order_address_select option[data-select2-tag='true']").val());
 });

The problem is when I'm typing text, and selecting it as a tag, event doesnt trigger for the first time. But when I'm typing text again, and selecting it, code alerts value of previously selected option. For example: I'm typing "aaa", selecting it, nothing happens, then I'm typing "bbb", selecting it, and got alert with "aaa"

Share Improve this question edited Jan 24, 2018 at 14:28 Adrien Brunelat 4,6624 gold badges33 silver badges44 bronze badges asked Jan 23, 2018 at 16:15 Игорь БыстревскийИгорь Быстревский 43710 silver badges26 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

So, if anyone is interested, I found solution on select2 github repository, you just need to add an empty <option></option> to your <select>. And then it will work fine

Inside my change handler I get the selected option as

var data = $(this).select2("data")[0];

Like this:

$selectXXXXX.on('change', function (e) {
        var data = $(this).select2("data")[0];
        var cfg = configuraciones[data.id];
        app.usersFocusChange(data.id, cfg); 
});

Ref: select2 dox

You can resolve it by manipulating html :

$('#yourselect2').append("<option selected value='your_val'>your_text</option>"); 
发布评论

评论列表(0)

  1. 暂无评论