JavaScript控制两个列表框listbox左右交换数据的方法
本文实例讲述了JavaScript控制两个列表框listbox左右交换数据的方法。分享给大家供大家参考。具体分析如下:
这个功能我们经常用到,将左边列表框的元素移动到右边,或者将右边列表框的元素移动到左边,可以一次性全部移动
functionlistbox_moveacross(sourceID,destID){
varsrc=document.getElementById(sourceID);
vardest=document.getElementById(destID);
for(varcount=0;count<src.options.length;count++){
if(src.options[count].selected==true){
varoption=src.options[count];
varnewOption=document.createElement("option");
newOption.value=option.value;
newOption.text=option.text;
newOption.selected=true;
try{
dest.add(newOption,null);//Standard
src.remove(count,null);
}catch(error){
dest.add(newOption);//IEonly
src.remove(count);
}
count--;
}
}
}
//..
listbox_moveacross('countryList','selectedCountryList');下面是像是的演示效果代码,可以直接在浏览器内执行
Clickbelowbuttonstomoveselectedoptionsrightorleft.<br>
<table>
<tbody><tr>
<td>
<selectid="sourceSelect"size="10"multiple="">
<optionvalue="a">Afghanistan</option>
<optionvalue="b">Bahamas</option>
<optionvalue="c">Barbados</option>
<optionvalue="d">Belgium</option>
<optionvalue="e">Bhutan</option>
<optionvalue="f">China</option>
<optionvalue="g">Croatia</option>
<optionvalue="h">Denmark</option>
<optionvalue="i">France</option>
</select>
</td>
<td>
<buttononclick="listboxMoveacross('sourceSelect','destSelect');">>></button> <br>
<buttononclick="listboxMoveacross('destSelect','sourceSelect');"><<</button>
</td>
<td>
<selectid="destSelect"size="10"multiple="">
<optionvalue="a">Afghanistan</option>
<optionvalue="b">Bahamas</option>
<optionvalue="c">Barbados</option>
<optionvalue="d">Belgium</option>
<optionvalue="e">Bhutan</option>
<optionvalue="f">China</option>
<optionvalue="g">Croatia</option>
<optionvalue="h">Denmark</option>
<optionvalue="i">France</option>
</select>
</td>
</tr>
</tbody></table>
<script>
functionlistboxMoveacross(sourceID,destID){
varsrc=document.getElementById(sourceID);
vardest=document.getElementById(destID);
for(varcount=0;count<src.options.length;count++){
if(src.options[count].selected==true){
varoption=src.options[count];
varnewOption=document.createElement("option");
newOption.value=option.value;
newOption.text=option.text;
newOption.selected=true;
try{
dest.add(newOption,null);//Standard
src.remove(count,null);
}catch(error){
dest.add(newOption);//IEonly
src.remove(count);
}
count--;
}
}
}
</script>
希望本文所述对大家的javascript程序设计有所帮助。