2016-10-03 54 views
0

在我的应用程序中,用户根据团队选择不同的团队&,他选择了一些球员。现在用户正在更新他的团队选择。自从他选择了“皇家挑战者”球队&一些球员。他不允许他这样做,一旦他从“皇家挑战者”或任何球队中移除球员,那么只有他将被允许更新他的球队选择。 因此,在更新他的球队之前(在onChange()之前),我检查球员数&,如果球员数大于1,然后显示一个弹出信息通知他删除球员。 现在点击“确定”,他应该看到以前选择的球队名称。如何在JavaScript/jQuery中设置/重置先前选择的多选选项

这是我的代码。

const prevSelected = $('#teams :selected').map(function() {return $.trim($(this).text())}).get(); 
//prev selected value is : Kolkata,Delhi,Royal Challengers 
$('#teams').on('change', function(){ 
    const selected = $('#teams :selected').map(function() {return $.trim($(this).text())}).get(); 
    var count = $("#teamName").find("br").length;   

    if(count >= 1){   
     //here user is updating his team. 
     if(selected.indexOf('Royal Challengers') == -1){ 
      alert("There are currently "+count+" players with "+ teamName +". These players must be migrated to a different teams before you can remove the Team 'Royal Challengers' from this Tournament"); 
      // code to get the previous selected players 
      return; 
     } 
    } 

} 

我试过,但没有奏效 -

if(count >= 1){ 
    //user changes, if the new selected option contains other than "Royal Challengers" then display the pop up & clicking on "OK" display the previous selected teams.     
    if(selected.indexOf('Royal Challengers') == -1){      
     alert("-------"); 
     $(prevSelected).prop('selected', true); 
    } 
} 

请帮助。

+0

请详细说明。不能明白是什么问题 –

+0

谢谢@AnoopLL ....详细阐述。请看看。 –

+0

您可以使用JStorage来存储玩家,只要他点击确定,可以在jstorage中显示玩家 –

回答

0

这解决了我的问题 -

for(var i=0;i<selected.length;i++){ 
    if(selected[i]!=''){ 
     $('option:contains('+selected[i]+')').prop('selected', false); 
    } 
} 

for(var i=0;i<prevSelected.length;i++){ 
    if(prevSelected[i]!=''){ 
     $('option:contains('+prevSelected[i]+')').prop('selected', true);  
    } 
}