JavaScript

How to Perform Simple JavaScript Checkbox Validation

On various websites, a square-shaped box called a “checkbox” appears to accept all the terms and conditions before submitting a form. Similarly, the checkboxes are used in specific forms of information gathering, such as surveys, to get the users’ opinions. The validation of the checkboxes helps to ensure that the checkbox is marked or checked. It will be helpful to improve the user experience by alerting the user to any errors in the form before they are submitted.

This post will define the procedure for validating the checkbox in JavaScript.

How to Perform Simple JavaScript Checkbox Validation?

To perform checkbox validation, use the “checked” property of the checkbox element. If the checkbox is checked, it gives “true” else, it returns “false” for the “not-checked” checkbox.

Example

Create a checkbox in the form and submit it by marking or checking the checkbox. If you try to submit the form without checking the checkbox (accepting the terms and conditions), it will throw an error, and the form will not be submitted:

<form name="form" action="#">
 <input type="checkbox" id="accept"> I accept all the terms and conditions<br>
 <br><input type="button" value="Submit" onClick="validation()">
 <p id="error"></p>
</form>

 

Define a function “validation()” to validate the checkbox by showing an error message while submitting the form without marking the checkbox:

function validation()
{
 var checkbox = document.getElementById("accept");
 if (!checkbox.checked){
  document.getElementById("error").innerHTML = "You must accept the terms and conditions by checking the Checkbox";
  return false;
 }
 document.getElementById("error").innerHTML = "Thanks....";
 return true;
}

 

In the above-given code:

  • First, get the reference of the checkbox using its id.
  • Then, check whether the checkbox is checked/marked utilizing the “checked” property.
  • If the checkbox is not marked, show an error message and ask to mark the check box for submitting the form.

You can also use the syntax below to check whether the checkbox is marked:

if (checkbox.checked == false)

 

Output

We have provided the simplest method to validate the checkbox in JavaScript.

Conclusion

To perform simple JavaScript validation of the checkbox, utilize the “checked” property. It will check whether the checkbox is checked/marked by giving the boolean value on the checked or unchecked conditions. This post described the procedure for validating the checkboxes in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.