Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select2 onchange event only works once

I have a problem with the jQuery's 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.

If I search another time, it won't.

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

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");

});
like image 908
PartySoft Avatar asked Jul 18 '13 18:07

PartySoft


7 Answers

This is what I am using:

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

For latest jQuery users, this one should work:

$(document.body).on("change","#search_code",function(){
 alert(this.value);
});
like image 64
Steel Brain Avatar answered Oct 05 '22 20:10

Steel Brain


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

  • 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

Ref: 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>
like image 30
Nisarg Shah Avatar answered Oct 05 '22 20:10

Nisarg Shah


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.

like image 44
Keith Muenze Avatar answered Oct 05 '22 19:10

Keith Muenze


$('#search_code').select2({
.
.
.
.
}).on("change", function (e) {
      var str = $("#s2id_search_code .select2-choice span").text();
      DOSelectAjaxProd(e.val, str);
});
like image 23
HamidReza Avatar answered Oct 05 '22 18:10

HamidReza


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

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

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

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

.

formatSelection: function(item) {item.id =getRandomInt(1,200)}
like image 29
cpugourou Avatar answered Oct 05 '22 20:10

cpugourou


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

  • change
  • select2-opening
  • select2-open
  • select2-close
  • select2-highlight
  • select2-selecting
  • select2-removed
  • select2-loaded
  • select2-focus

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

like image 21
Dradge Avatar answered Oct 05 '22 20:10

Dradge


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

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-open handler being executed before the onchange handler.

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.

like image 23
Stephane Avatar answered Oct 05 '22 18:10

Stephane