简体   繁体   中英

select2 'change' event doesn't trigger for the first time

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"

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

您可以通过操作 html 来解决它:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM