如何在不使用ASP.NET中的复选框控件的id属性的情况下阅读动态复选框?

时间:2011-04-22 03:47:14

标签: asp.net webforms

我有一个Web应用程序,我在运行时动态生成并显示复选框。每个复选框对应一个项目。我需要找到选中的项目。但是我生成控件时无法在Checkbox控件的ID属性中设置项目的ID,因为同一项目可以在网页上多次出现.ID属性使我能够使用Page.Form()方法,但现在我不能用。请建议另一种方法来查找选中的复选框。

1 个答案:

答案 0 :(得分:1)

如果您使用JQUERY,您可以为每个复选框分配一个公共类,然后使用“类选择器”来获取页面上所有具有相同类的项目数组。有了它,您可以遍历数组并识别已检查的项目。 相关代码如下所示:

<head>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        function findCheckedBoxes() {
            var AllBoxes = $(".productCheckBox");
            for(i=0;i<AllBoxes.length; i++)
            {
                if(AllBoxes[i].checked)
                {
                    //do something with it...
                    alert(AllBoxes[i].value);
                }
                }
        }

    </script>
</head>
<body>
    <form id="form1" runat="server" onsubmit="return validatefields();">
    <input id="Checkbox1" type="checkbox" class="productCheckBox" value="one" />One<br />
    <input id="Checkbox2" type="checkbox" class="productCheckBox" value="two" />Two<br />
    <input id="Checkbox3" type="checkbox" class="productCheckBox" value="three" />Three<br />
    <input id="Checkbox4" type="checkbox" class="productCheckBox" value="four" />Four<br />
    <input id="Button2" type="button" value="button" onclick="findCheckedBoxes()" />
    </form>
</body>
</html>