根据第一个选择下拉列表填充其他选择下拉列表

时间:2011-08-27 11:07:44

标签: java javascript struts

我正在使用struts 1.2,我有一个非常一般的要求,我有两个下面的下拉框。现在我想在选择类别时,它应该填充subcatoegory选择框。我尝试使用javascript,但没有运气。

请某人指导我。

我可以通过使用html select来实现。

 <html:select property="cat" onchange="getSubcatValue(this.value);">    
<html:option value="0">Category</html:option>
<html:optionsCollection name="PostaddForm" property="categoryList"  label="catName" value="catID"/>
</html:select>



 <html:select property="subCat" >
<html:option value="0">Category</html:option>
<html:optionsCollection name="PostaddForm" property="subCategoryList"  label="label" value="value"/>
</html:select>

1 个答案:

答案 0 :(得分:0)

为什么不尝试使用jQuery,它会是这样的:

<select id="mainDropDown" onchange="getSubcatValue()">
     //Options for mainDropDown list
</select>

<select id="subDropDown"></select>

<script type="text/javascript>
    function getSubcatValue() 
    {
        var chosenValue = $("#mainDropDown").val();
        var options = $('#subDropDown').prop('options');
        options = [];
        if (chosenValue == "something") {
            for (var i = 0 ; i < 10 ; i++) {
                options[i] = new Option(i+1, i); // populate the subDropDown with 10 options: 1, 2 ,3, 4, etc... 
                //The 1st parameter is the text for the option, the 2nd parameter is the value of the option
            }
        }
    }
</script>

编辑:根据Anthony评论,我想补充一点,for循环仅用于演示目的,以帮助您了解如何填充选项。在现实世界中,例如,在我自己的Web应用程序中,我进行了Ajax调用以检索XML中的选项数据以填充下拉列表。

希望它有所帮助!

相关问题