【JS】左右两个Select的左项全倒右边、左选择项到右边、右边清除选择项、右边全清四大操作
【图】
【HTML代码】
<table border="1"> <tr> <td width="200px"> <select id="leftSelect" multiple="multiple" style="width:200px;height:200px;"> </select> </td> <td width="80px" align="center"> <br/><br/> <a href="javascript:addAll();" class="btn btn-primary">>></a> <br/><br/> <a href="javascript:addSelected();" class="btn btn-primary">></a> <br/><br/> <a href="javascript:removeSelected();" class="btn btn-primary"><</a> <br/><br/> <a href="javascript:removeAll();" class="btn btn-primary"><<</a> <br/><br/> </td> <td width="200px"> <select id="rightSelect" multiple="multiple" style="width:200px;height:200px;"> </select> </td> </tr> </table>
【JS代码】
function addAll(){ var leftOpts=document.getElementById("leftSelect").options; var rightOpts=document.getElementById("rightSelect").options; rightOpts.length=0; for(var i=0,n=leftOpts.length;i<n;i++){ var opt=leftOpts.item(i); rightOpts.add(new Option(opt.text,opt.value)); } } function removeAll(){ var rightOpts=document.getElementById("rightSelect").options; rightOpts.length=0; } function addSelected(){ var leftOpts=document.getElementById("leftSelect").options; var seletedArr=[]; for(var i=0,n=leftOpts.length;i<n;i++){ var opt=leftOpts.item(i); if(opt.selected){ seletedArr.push(new Option(opt.text,opt.value)); } } var rightOpts=document.getElementById("rightSelect").options; for(var j=0;j<seletedArr.length;j++){ var opt=seletedArr[j]; var exist=false; for(var i=0,n=rightOpts.length;i<n;i++){ var optInner=rightOpts.item(i); if(optInner.value==opt.value){ exist=true; break; } } if(exist==false){ rightOpts.add(new Option(opt.text,opt.value)); } } } function removeSelected(){ var rightOpts=document.getElementById("rightSelect").options; var n=rightOpts.length-1; for(var i=n;i>=0;i--){ var opt=rightOpts[i]; if(opt.selected==true){ rightOpts[i]=null; } } }
END