Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('change');

If when you make a selection in one of these two elements you want to reset the other to the initial value, the onChange event is triggered by the value setting and the system enters an infinite loop. The same happens if you use

$('#id1').val('xyz').trigger('change.select2')
like image 497
Yiannis Avatar asked Sep 05 '25 03:09

Yiannis


1 Answers

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 triggered
     if (typeof state!='undefined' && state){
        console.log('change #1 is triggered from code');
        return false;  
     }
    
     console.log('change #1 is from ui');
    
   
  });
  
  $('#id2').on("change",function(e, state){
    
     
     //we check state if exists and is true then event was triggered
     if (typeof state!='undefined' && state){
        console.log('change #2 is triggered from code');
        return false;  
     }
    
    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);  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Select 1</span>
<select id="id1">
  <option val="1" >1</option>
  <option val="2" >2</option>
  <option val="3" >3</option>
</select>

<span>Select 2</span>
<select id="id2">
  <option val="1" >1</option>
  <option val="2" >2</option>
  <option val="3" >3</option>
</select>
like image 135
Maciej Sikora Avatar answered Sep 08 '25 00:09

Maciej Sikora