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>
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>
function ValidateForm(form){ ErrorText= ""; if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == false ) ) { alert ( "Please choose your Gender: Male or Female" ); return false; } if (ErrorText= "") { form.submit() } }
<form name="feedback" action="#" method=post> Your Gender: <input type="checkbox" name="gender" value="Male"> Male <input type="checkbox" name="gender" value="Female"> Female <input type="reset" value="Reset"> <input type="button" name="SubmitButton" value="Submit" onClick="ValidateForm(this.form)"> </form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.