select2 onchange event only works once
Asked Answered
C

8

37

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

});
Caspar answered 18/7, 2013 at 18:55 Comment(5)
Have you tried this in the debugger? Are you getting any error messages especially when the very first onchange event happens?Downstream
try $(document).on('change', 'span#search_code', function(... and tell if it works. Replace span by div if #search_code is id to a div or by "element" whatever type of "element" it is.Spitter
yeah it is a false alarm.. i was actually selecting the same element so it won't trigger the change event in that case...Caspar
oh but there is a problem .. the onchange doesn't trigger on the same index... So if you have an ajax select that has say 2 results and you selected index 1 .. then you search again..and you have X results and again select index 1 .. the contents could be different but the same index.. So I have to force onchange everytime actually. how can I do that?Caspar
I found this post that's similar to my problem, but how does modify my code? #16062564Caspar
P
48

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);
});
Peyton answered 11/8, 2013 at 22:11 Comment(1)
loved the second suggestion. clean, short and functional.Serve
V
21

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>
Vineyard answered 12/9, 2017 at 11:25 Comment(0)
P
18

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.

Propel answered 2/5, 2014 at 22:53 Comment(3)
good one... i modified for dynamic dropdown as follows: $(document).on('select2-selecting','#search_code',function(e){ $('#search_code').select2('data', e.choice); });Veljkov
I noticed the same behavior as well. If an item was already selected, the change event did not fire when selecting another item. Take a look at @cpugourou answer. Ensuring the item has an unique Id gets the Change event to fire.Roye
I don't understand your introductory comment... You care to be more vernose ?Frug
B
9
$('#search_code').select2({
.
.
.
.
}).on("change", function (e) {
      var str = $("#s2id_search_code .select2-choice span").text();
      DOSelectAjaxProd(e.val, str);
});
Brasher answered 6/2, 2016 at 11:32 Comment(2)
How does this answer the question? What's different from the original problem?Walt
It looks exactly the same to me. You're claiming that you're answering OP's question. How does this answer the question? What was wrong? What's now right?Walt
S
8

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)}
Sarnen answered 6/2, 2015 at 1:48 Comment(0)
E
3

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.

Edwyna answered 14/4, 2016 at 14:0 Comment(0)
F
2

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.

Frug answered 29/11, 2017 at 21:21 Comment(0)
P
0

if you are working with stimulus js then write in connect methode:

$("#idOfSelect2").on('change', function(){ //write your logic here})

if you are working with vanilla js then you can call a function on page load and do the same thing like above:

Puppetry answered 14/12, 2022 at 8:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.