select2 onchange event only works once

PartySoft picture PartySoft · Jul 18, 2013 · Viewed 114.4k times · Source

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

});

Answer

Steel Brain picture Steel Brain · Aug 12, 2013

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