如何在组合框中动态添加值?

时间:2014-05-26 14:57:20

标签: java javascript jsp

这是HTML代码,我用来动态加载值

<select name="type" id="type" style="width: 200px;" onChange="settype();">
<option value="Education">Education</option>
<option value="Hospital">Hospital</option>
<option value="Marriage">Marriage</option>      
</select> 
<select name="subtype" id="subtype" style="width: 200px;"></select>

这里的值是根据第一个组合框值

动态添加的
function settype() {            
        var hospital = new Array("Govt", "Private Hospital");
        var marriage = new Array("Marriage Hall", "Temple", "Resorts");
        var education = new Array("School", "College", "univercity");

        var select_Register_For = document.getElementById(type);
        var select_type = document.getElementById(subtype);
        var selected_sport = select_Register_For.options[select_Register_For.selectedIndex].value; 

          if (selected_sport === "Education") {
            for (var i = 0; i < education.length; i++) {
                var option = document.createElement("option");
                option.text = education[i].value;
                option.value = education[i].value;
                select_type.add(option,0);
            }
        }
    };

1 个答案:

答案 0 :(得分:1)

有些人认为可能会引起问题。

  • 使用document.getElementById("type")代替document.getElementById(type),同样代替subtype
  • 使用education[i]代替education[i].value从索引i的数组中获取值。

这是一个有一些修改的功能:

function settype() {
    var hospital = new Array("Govt", "Private Hospital");
    var marriage = new Array("Marriage Hall", "Temple", "Resorts");
    var education = new Array("School", "College", "univercity");

    var select_Register_For = document.getElementById("type");
    var select_type = document.getElementById("subtype");
    var selected_sport = select_Register_For.options[select_Register_For.selectedIndex].value;

    if (selected_sport === "Education") {
        for ( var i = 0; i < education.length; i++) {
            var option = document.createElement("option");
            option.text = education[i];
            option.value = education[i];
            select_type.add(option, 0);
        }
    }
};