转自 http://www.blogjava.net/supercrsky/articles/208149.html
< html >
< head >< title > 选择框测试 </ title ></ head >
< script >
function change()
{
// 得到的是一个option数组
var sel = document.getElementById( " test1 " );
alert(sel.length);
alert(sel[sel.selectedIndex].value);
}
function output()
{
var sel = document.getElementById( " test1 " );
for ( var i = 0 ; i < sel.length; i ++ )
{
alert(sel[i].value);
}
}
function create()
{
var sel = document.getElementById( " test2 " );
if (sel.length > 0 )
{
for ( var i = 0 ;i < sel.length; i ++ )
{
if (sel[i].value == " beijing " )
{
alert('已经存在');
// break;
return ;
}
}
}
var option = new Option( " 北京 " , " beijing " );
sel.options.add(option);
}
function clears()
{
var sel = document.getElementById( " test " );
sel.length = 0 ;
alert('已经清除');
}
function createTest()
{
var sel = $( " test " );
var text = new Array( " 北京 " , " 天津 " , " 上海 " );
var value = new Array( " beijing " , " tianjing " , " shanghai " );
for ( var i = 0 ;i < text.length; i ++ )
{
if (sel.length > 0 )
{
for ( var j = 0 ; j < sel.length; j ++ )
{
if (sel[j].value == value[i])
{
alert( " 请不要重复创建 " );
return ;
}
}
}
var option = new Option(text[i],value[i]);
sel.options.add(option);
}
}
// ajax中快速取得dom对象的方法
function $(id)
{
return document.getElementById(id);
}
</ script >
< body >
< select onChange ="alert(this.value);" id ="test" >
< option value ="beijing" > 北京 </ option >
< option value ="tianjing" > 天津 </ option >
< option value ="shanghai" > 上海 </ option >
</ select >
< input type ="button" value ="清除" onclick ="clears();" />
< input type ="button" value ="创建" onclick ="createTest()" />
< hr />
< select onChange ="change();" id ="test1" >
< option value ="beijing" > 北京 </ option >
< option value ="tianjing" > 天津 </ option >
< option value ="shanghai" > 上海 </ option >
</ select >
< select id ="test2" >
</ select >
< input type ="button" value ="输出" onclick ="output();" /> < br />
< input type ="button" value ="创建" onclick ="create();" />
</ body >
</ html >