I am trying to validate some groups of checkboxes using Jq but I don’t know where I am doing wrong.
I use the same code to validate other forms (but not checkboxes and is working fine.
form.php
<form id=frm_ch>
<td><input type="checkbox" name="g1" id="h1" value="1" /></td>
<td><input type="checkbox" name="g1" id="d1" value="2" /></td>
<td><input type="checkbox" name="g1" id="a1" value="3" /></td>
<td><input type="checkbox" name="g2" id="h2" value="1" /></td>
<td><input type="checkbox" name="g2" id="d2" value="2" /></td>
<td><input type="checkbox" name="g2" id="a2" value="3" /></td>
<td><input type="checkbox" name="g3" id="h3" value="1" /></td>
<td><input type="checkbox" name="g3" id="d3" value="2" /></td>
<td><input type="checkbox" name="g3" id="a3" value="3" /></td>
validate.js
//global vars
var frm_ch = $("#frm_ch");
var g1 = $("name=g1");
var g2 = $("name=g2");
var g3 = $("name=g3");
var cInfo = $("#cInfo");
frm_ch.submit(function(){
if(valG1() & valG2() & valG3()){
var g1 = $("name=g1").attr('value');
var g2 = $("name=g2").attr('value');
var g3 = $("name=g3").attr('value');
//validate functions are all the same so I am posting just one:
function valG1(){
//if it's NOT valid
if($('input[name=g1]:checked').size() == 0){
cInfo.text("Please check a Checkbox");
cInfo.addClass("error");
return false;
}
//if it's valid
else{
cInfo.text("");
cInfo.removeClass("error");
return true;
}
}
You have syntax errors. You are missing two closing curly braces and closing parenthesis (e.g. add
to the end of your code). Also your submit handler is not returning anything. Additionally, as a part of DRY (do not repeat yourself) principle, you don’t want to have three different functions valG1, valG2, valG3 that essentially do the same thing. This code works.