Reputation: 95
In my aspx page i am having a checkbox list ..It has binded values from a table.. I need to validate the checkbox list ..I tried the following script
var checkBoxCount = 0;
var elements = document.getElementById('<%=ChkBoxList.ClientID%>');
for(i=0; i<elements.length;i++)
{
if(elements[i].checked)
checkBoxCount++;
}
if (checkBoxCount == 0)
{
alert("Please choose atleast one");
return false;
}
But I can't get the required output, it requires to select all the values in the checkbox list ..My need is atleast only one item must be selected from the checkbox list.. Using javascript
Thanks in advance...
Upvotes: 1
Views: 2691
Reputation: 95
var k=0; var ControlRef = document.getElementById('ChkBoxList'); var CheckBoxListArray = ControlRef.getElementsByTagName('input'); for (var i=0; i
Upvotes: 0
Reputation: 274838
You will have to show us your generated html.
However, here is a working example:
<html>
<body><form name="myform" method="POST" action="" onsubmit="return validate();">
<input type="checkbox" name="mybox" value="1" /> 1
<input type="checkbox" name="mybox" value="2" /> 2
<input type="checkbox" name="mybox" value="3" /> 3
<input type="checkbox" name="mybox" value="4" /> 4
<input type="checkbox" name="mybox" value="5" /> 5
<input type="submit" value="Submit Form" />
</form>
<script type = "text/javascript">
function validate() {
var checkBoxCount = 0;
for (var i = 0; i< 5; i++) {
if(document.myform["mybox"][i].checked){
checkBoxCount ++;
}
}
if (checkBoxCount == 0) {
alert ("Tick a box!");
return false;
}
return true;
}
</script>
</body>
</html>
Upvotes: 0
Reputation: 1410
function readListControl()
{
var tableBody = document.getElementById('CheckBoxList1').childNodes[0];
for (var i=0;i<tableBody.childNodes.length; i++)
{
var currentTd = tableBody.childNodes[i].childNodes[0];
var listControl = currentTd.childNodes[0];
if ( listControl.checked == true )
alert('#' + i + ': is checked');
}
}
Upvotes: 1
Reputation: 31913
document.getElementById
returns an element, not an array.
One way to do this would be to get the container and iterate through the inputs, like so:
var container = document.getElementById('<%=ChkBoxList.ClientID%>').parentNode;
var inputs = container.getElementsByTagName('input');
for (var i=0; i<inputs.length; i++) {
if (typeof inputs[i] = "checkbox") {
// statements
}
}
You may also want to qualify the inputs with more conditional statements. This just gives you the broad brush strokes.
Upvotes: 0