在开发动态网站程序是,经常会遇到将下拉列表中的选项进行多项移除或者多项移入。实例如下:
javascript代码:
<script language="javascript">
function allsel(n1,n2)
{
while(n1.selectedIndex!=-1)
{
var indx=n1.selectedIndex;
var t=n1.options[indx].text;
n2.options.add(new Option(t));
n1.remove(indx);
}
}
</script>
html代码:
<select name="sel_place1" size="6" multiple class="wenbenkuang" id="sel_place1" style="width:100px " >
<option value="sel1">甘肃省</option>
<option value="sel2">辽宁省</option>
<option value="sel3">黑龙江省</option>
<option value="sel4">吉林省</option>
<option value="sel5">浙江省</option>
</select>
<input name="sure1" type="button" id="sure1" onClick="allsel(document.form1.sel_place2,document.form1.sel_place1);" value="<<">
<input name="sure2" type="button" id="sure2" onClick="allsel(document.form1.sel_place1,document.form1.sel_place2);" value=">>" align="center" height="2">
<select name="sel_place2" size="6" multiple class="wenbenkuang" id="sel_place2" style="width:100px "></select>
本实例主要应用javascript的while循环语句,判断如果select元素的selectIndex属性值不为-1,则获取在下拉列表中的选中项的索引值和对应文本,然后应用select元素对象的add()方法将此选项添加到另一个下拉列表中,并应用select元素对象的remove()方法移除当前下拉列表中的此选项。
不过以上代码还有不足之处,虽说是把select列表中的选项移入到另外个select列表中,但是,只是获取到原列表中的text值,并没有得到原来的value值,怎么办呢?原来new Option()方法是可以添加value值的,如new Option(t,v);这样就可以让原有的选项把text跟value值一块移入到另外的select列表中了。javasript代码修改为:
<script language="javascript">
function allsel(n1,n2)
{
while(n1.selectedIndex!=-1)
{
var indx=n1.selectedIndex;
var t=n1.options[indx].text;
var v=n1.options[indx].value;
n2.options.add(new Option(t,v));
n1.remove(indx);
}
}
</script>