Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript checkbox form validation

I'm trying to use this link as my resource: http://www.w3schools.com/js/js_form_validation.asp

I understand how it works for textboxes, but how do you make it detect form validation for checkboxes? For example, if I have a page lined with checkboxes (all with the same "name" value), I want to make sure that at least one of the boxes is checked... How do I do this? I'm a little confused about what post request is sent if a checkbox is not checked, and how javascript should catch it. Thank you.

Edit----

Got it to work, here's some code for future people:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function Validate(){
   if(!validateForm()){
       alert("Something happened");
       return false;
   }
return true
}
function validateForm()
{
    var c=document.getElementsByTagName('input');
    for (var i = 0; i<c.length; i++){
        if (c[i].type=='checkbox')
        {
            if (c[i].checked){return true}
        }
    }
    return false;
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return Validate()" method="post">
Value: <input type="checkbox" name="fname" value="value">
Value2: <input type="checkbox" name="fname" value="value2">
...<more boxes here>
<input type="submit" value="Submit">
</form>
</body>
</html>
like image 879
de1337ed Avatar asked May 25 '26 22:05

de1337ed


1 Answers

Here is an example that does what you are asking and can be tested within this page:

function Validate(){
   if(!validateForm()){
       alert("You must check atleast one of the checkboxes");
       return false;
   }
return true
}
function validateForm()
{
    var c=document.getElementsByTagName('input');
    for (var i = 0; i<c.length; i++){
        if (c[i].type=='checkbox')
        {
            if (c[i].checked){return true}
        }
    }
    return false;
}
<form name="myForm" action="demo_form.asp" onsubmit="return Validate()" method="post">
Option 1: <input type="checkbox" name="option1" value="1"><br />
Option 2: <input type="checkbox" name="option2" value="2"><br />
<input type="submit" value="Submit Form">
</form>
like image 81
Tim Penner Avatar answered May 27 '26 11:05

Tim Penner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!