日期:2014-05-16  浏览次数:20309 次

JS动态逐级添加select下拉框
动态获取select中的options数量:
        Var size = document.getElementById("ddlResourceType").options.length;

动态删除select中的所有options:
       document.getElementById("ddlResourceType").options.length=0;

动态删除select中的某一项option:
       document.getElementById("ddlResourceType").options.remove(indx); 

动态添加select中的项option:
document.getElementById("ddlResourceType").options.add(new Option(text,value));

上面在IE和FireFox都能测试成功,希望以后你可以用上。


其实用标准的DOM操作也可以,就是document.createElement,appendChild,removeChild之类的。

取值方面
    function getvalue(obj)
    {
        var m=obj.options[obj.selectedIndex].value
        alert(m);//获取value
        var n=obj.options[obj.selectedIndex].text
        alert(n);//获取文本
    }

==============================================================================
1 检测是否有选中
if (objSelect.selectedIndex > - 1 ) {
// 说明选中
} else {
// 说明没有选中
}

将option设为选中:document.getElementById("province").options.selected = true;

2 删除被选中的项
objSelect.options[objSelect.selectedIndex] = null ;

3 增加项
objSelect.options[objSelect.length] = new Option( " 你好 " , " hello " );

4 修改所选择中的项
objSelect.options[objSelect.selectedIndex] = new Option( " 你好 " , " hello " );

5 得到所选择项的文本
objSelect.options[objSelect.selectedIndex].text;

6 得到所选择项的值

objSelect.options[objSelect.selectedIndex].value;

7.所选择项设置为选中
objSelect.options[objSelect.selectedIndex].selected = true;



例子:代码 
1.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
2."http://www.w3.org/TR/html4/loose.dtd">  
3.<html>  
4.<head>  
5.<meta http-equiv="Content-Type" content="text/html; charset=gb2312">  
6.<title>城市区域4级下拉框</title>  
7.<script>  
8.    function f1(v){  
9.        //alert(v);  
10.        //清除后面的项  
11.        document.getElementById("object2").options.length=0 
12.        document.getElementById("object3").options.length=0 
13.        document.getElementById("object2").style.display="none";  
14.        document.getElementById("object3").style.display="none";  
15.          
16.          
17.        var s  =  document.getElementById("object1");     
18.        if(v=="北京"){  
19.            var option0  =   new  Option("东城区","a1");  
20.            var option1  =   new  Option("西城区","a2");  
21.            var option2  =   new  Option("朝阳区","a3");  
22.            s.options[0] = option0;  
23.   &nb