如何在JavaScript/jQuery中设置/重置先前选择的多选择选项

How to set/Reset the previously selected multi Select option in JavaScript/jQuery

本文关键字:选择 选项 设置 JavaScript jQuery      更新时间:2023-09-26

在我的应用程序中,用户选择了不同的团队&根据球队,他选择一些球员。现在用户正在更新他的团队选择。自从他选择了"皇家挑战者"团队以来;一些球员。他不允许这样做,一旦他从"皇家挑战者"或任何球队中删除了球员,那么只有他才可以更新他的球队选择。因此,在更新他的团队之前(在onChange()之前),我正在检查球员计数&如果玩家数大于1,则显示一个弹出窗口,通知他删除玩家。现在单击"OK",他应该看到之前选择的球队名称。

这是我的代码。

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

请帮。

这就解决了我的问题-

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