Checkbox Validation using jQuery?

How to validate the checkbox using Jquery?

In the HTML form have multiple chekcbox in same using html array element. That time we will use three types of checkbox validation for checked or not.

Multiple checkbox validation has three types.
  • Checkbox validation using Id
  • Checkbox validation using name
  • Checkbox validation using div tag
Let we see via examples:

Take the below html/aspx code likes ...

<form>
<div id="checkboxId">
<input type="checkbox" name="chkBox[]" id="chkBox[]">
<input type="checkbox" name="chkBox[]" id="chkBox[]">
<input type="checkbox" name="chkBox[]" id="chkBox[]">
</div>

<input type="button" name="Btnaction"
value="submit" onclick="return validateId();">
</form>
</div>

// Calling jquery file.
<script language="javascript" src="jquery.js" type="text/javascript"></script>

1. Checkbox validation using Id

<script language="javascript">
function validateId()
{
var selector_checked = $("input[@id=chkBox]:checked").length;
alert(selector_checked);
if (selector_checked == 0)
{
return false;
}
else if (selector_checked == 0)
{
return false;
}
else
{
return true;
}
}
</script>

2. Checkbox validation using Name

Replace the function name from 'validateId' to 'validateName' in the above html/aspx code.

function validateName()
{
var selector_checked = $("input[@name=chkBox]:checked").length;
alert(selector_checked);
if (selector_checked == 0)
{
return false;
}
else if (selector_checked == 0)
{
return false;
}
else
{
return true;
}
}

3. Checkbox validation using Div tag

Replace the function name from 'validateName' to 'validateDiv' in the above html/aspx code.

function validateDiv()
{
if($("#checkboxId input[type='checkbox']:checked").length > 0)
{
return true;
}
}

4. Single checkbox validation.

<div>
<input type="checkbox" name="chkBox[]" id="chkTCAgree" />Agree terms and condition
text here<br />
<input type="button" name="Btnaction" value="submit" onclick="return validateTC();" />
</div>

function validateTC() {
var agree = $('#chkTCAgree').attr('checked');
if (!agree) {
alert("please accept the terms and conditions");
return false;
}
}

Enjoy the technology!

Leave a Reply