Reputation: 3684
I have a web application in which I am dynamically generating and displaying checkboxes at runtime. Each checkbox corresponds to an item. I need to find which items are selected. However I cannot set the id of the item in the ID attribute of Checkbox control while generating the control as the same item can appear multiple times on the web page.The ID attribute enables me to use the Page.Form() method but now I cannot use. Please suggest an alternate method to find which checkboxes are checked.
Upvotes: 0
Views: 664
Reputation: 5084
If you use JQUERY you can assign a common class to each checkbox and then use a "class selector" to get an array of items on a page that all have the same class. With that you may iterate through the array and identify which items have been checked. The relevant code will look something like:
<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>
Upvotes: 1