Select2 trigger(“change”) creates an infinite loop

不打扰是莪最后的温柔 提交于 2019-12-13 06:55:06

问题


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')

回答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 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>



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



回答3:


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

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


来源:https://stackoverflow.com/questions/39147672/select2-triggerchange-creates-an-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!