Reputation: 1
I tried using JavaScript samples that I found here and other places. The problem is that I am using a Table control working at the server, so the JavaScript I was using does not recognizes the checkboxes which are server side as well. I kept getting the same error message over and over. I got 20 rows with 2 columns each, one for the checkbox and one for a statement that the user has to validate by checking the box before they can submit. The user has to physically check each box. If any checkbox is not checked, then I would like to sees a popup message saying they must check all boxes, Else I am doing a redirect to another page, of course all this on the button click event. This all on Visual Studio 2010, using C#, the back-end is SQL Server.
Here a sample of the JS I was using:
function checkCheckBoxes() {
if (document.frmTest. CheckBox1.checked == false &&
document.frmTest. CheckBox2.checked == false &&
document.frmTest. CheckBox3.checked == false &&
document.frmTest. CheckBox4.checked == false &&
document.frmTest. CheckBox5.checked == false &&)
{
alert ('You must check all the checkboxes!');
return false;
}else{
return true;
}
}
then,
<form onsubmit="return checkCheckBoxes();" action="">
<input type="checkbox" name=" CheckBox1" value="1">
<input type="checkbox" name=" CheckBox2" value="2">
<input type="checkbox" name=" CheckBox3" value="3">
<input type="checkbox" name=" CheckBox4" value="4">
<input type="checkbox" name=" CheckBox5" value="5">
<input type="submit" value="Submit!" />
</form>
But I realized that the checkboxes can't be server control but JavaScript controls. Thanks.
Upvotes: 0
Views: 2060
Reputation: 25435
You need something like this
var pass = true;
for (var i = 0; i < form.elements.length; i++ )
{
if (form.elements[i].type == 'checkbox')
{
if (form.elements[i].checked == false)
{
pass = false;
}
}
}
if(!pass)
{
alert ('You must check all the checkboxes!');
}
return pass;
Hope this helps.
Upvotes: 5
Reputation: 935
Use querySelectorAll to check for any unchecked check boxes. If there are any, throw the error message, else postback.
function checkCheckboxes(){
if(document.querySelectorAll('input[type="checkbox"]:not(:checked)').length > 0){
alert("all checkboxes must be checked");
return false;
} else{
return true;
}
}
Note: this will only work in Modern browsers Firefox 3.1+, IE8+ (only in IE8 standards mode), and Safari 3.1+
Upvotes: 0
Reputation: 13501
You can get the HTML ID of the checkboxes by using the C# ClientID property. Insert that ID into your Javascript, and you will then be able to select the relevant checkboxes and do whatever you like with them.
Upvotes: 1