Skip to content Skip to sidebar Skip to footer

Select2 Trigger("change") Creates An Infinite Loop

Let say there are two select2 elements on the page, both using the 'onChange'. In order to programmatically set a value in one select2 element you use $('#id1').val('xyz').trigger

Solution 1:

To avoid inifinite loop use trigger method parameters to distinguish event calls, in trigger method usage add parameter and in event callback check if paramater exists, when parameter exists that means that event was triggered from code, if no, that means it is event from ui.

Check how it works on this code example.

$(function(){

  $('#id1').on("change",function(e, state){
    
     //we check state if exists and is true then event was triggeredif (typeof state!='undefined' && state){
        console.log('change #1 is triggered from code');
        returnfalse;  
     }
    
     console.log('change #1 is from ui');
    
   
  });
  
  $('#id2').on("change",function(e, state){
    
     
     //we check state if exists and is true then event was triggeredif (typeof state!='undefined' && state){
        console.log('change #2 is triggered from code');
        returnfalse;  
     }
    
    console.log('change #2 is from ui');
   
  });
  
  
});


/**TEST CODE TO TRIGGER CHECK **/setTimeout(function(){  
$('#id1').val('1').trigger('change',[true]);  //here is paramater - [true]
$('#id2').val('2').trigger('change',[true]);//here is paramater - [true]

$('#id1').val('3').trigger('change',[true]);  //here is paramater - [true]
$('#id2').val('3').trigger('change',[true]);//here is paramater - [true]
  
},1000);  
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><span>Select 1</span><selectid="id1"><optionval="1" >1</option><optionval="2" >2</option><optionval="3" >3</option></select><span>Select 2</span><selectid="id2"><optionval="1" >1</option><optionval="2" >2</option><optionval="3" >3</option></select>

Solution 2:

I created a guard function in my case. I used the event object and checked for undefined. When undefined I know its code so I just bail out of the function. That way you can run the code on initial click then the artificial ones get ignored.

$("#id1").on('change',function(e){
   if(e.originalEvent === undefined)return;//bail out if code caused it//do stuff here
});

Solution 3:

In this answer we see that is not the way to set a select2 value, but:

$('#id1').select2("val", "xyz");

Post a Comment for "Select2 Trigger("change") Creates An Infinite Loop"