2016-10-03 55 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);  
    } 
}