這篇文章主要介紹了JavaScript控制兩個(gè)列表框listbox左右交換數(shù)據(jù)的方法,實(shí)例分析了javascript操作列表框listbox的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
本文實(shí)例講述了JavaScript控制兩個(gè)列表框listbox左右交換數(shù)據(jù)的方法。分享給大家供大家參考。具體分析如下:
這個(gè)功能我們經(jīng)常用到,將左邊列表框的元素移動(dòng)到右邊,或者將右邊列表框的元素移動(dòng)到左邊,可以一次性全部移動(dòng)
代碼如下:
function listbox_moveacross(sourceID, destID) {
var src = document.getElementById(sourceID);
var dest = document.getElementById(destID);
for(var count=0; count < src.options.length; count++) {
if(src.options[count].selected == true) {
var option = src.options[count];
var newOption = 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); // IE only
src.remove(count);
}
count--;
}
}
}
//..
listbox_moveacross('countryList', 'selectedCountryList');
下面是像是的演示效果代碼,可以直接在瀏覽器內(nèi)執(zhí)行
代碼如下:
Click below buttons to move selected options right or left.<br>
<table>
<tbody><tr>
<td>
<select id="sourceSelect" size="10" multiple="">
<option value="a">Afghanistan</option>
<option value="b">Bahamas</option>
<option value="c">Barbados</option>
<option value="d">Belgium</option>
<option value="e">Bhutan</option>
<option value="f">China</option>
<option value="g">Croatia</option>
<option value="h">Denmark</option>
<option value="i">France</option>
</select>
</td>
<td>
<button onclick="listboxMoveacross('sourceSelect', 'destSelect');">>></button> <br>
<button onclick="listboxMoveacross('destSelect', 'sourceSelect');"><<</button>
</td>
<td>
<select id="destSelect" size="10" multiple="">
<option value="a">Afghanistan</option>
<option value="b">Bahamas</option>
<option value="c">Barbados</option>
<option value="d">Belgium</option>
<option value="e">Bhutan</option>
<option value="f">China</option>
<option value="g">Croatia</option>
<option value="h">Denmark</option>
<option value="i">France</option>
</select>
</td>
</tr>
</tbody></table>
<script>
function listboxMoveacross(sourceID, destID) {
var src = document.getElementById(sourceID);
var dest = document.getElementById(destID);
for(var count=0; count < src.options.length; count++) {
if(src.options[count].selected == true) {
var option = src.options[count];
var newOption = 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); // IE only
src.remove(count);
}
count--;
}
}
}
</script>
希望本文所述對(duì)大家的javascript程序設(shè)計(jì)有所幫助。
更多信息請(qǐng)查看IT技術(shù)專欄