Validate Checkbox Using jQuery

Validate Checkbox

How to validate checkbox using jQuery ?

This is a simple way to check whether the checkbox is checked or not. So this way we can validate the checkbox. A single line of code will provide the status of checkbox using jQuery or a single line of code will validate checkbox.

jquery needed to Validate Checkbox Using jQuery

if($("#myCheck").is(':checked')){
   alert('Checkbox is checked'); // checked
}
else {
   alert('Checkbox not checked'); // unchecked
}

The above method uses “is” selector and it returns true and false based on checkbox status.

HTML for Validate Checkbox Using jQuery

<input type="checkbox" id="myCheck" />

Here we check whether the checkbox is checked or not. If the checked box is checked then it return status as “checked”.

Similar methods to validate checkbox

var isChecked = $('#myCheck').prop('checked');

“prop()” will return status as true or false unlike “attr()” which returns checked or undefined. The jQuery prop() method provides a simple and reliable way to track down the status of checkboxes. It works well in all condition because every checkbox has checked property which specifies its checked or unchecked status.

var isChecked = $('#myCheck:checked').val()?true:false;

Here we use the jQuery “:checked” selector to check the status of checkboxes. $(‘#myCheck:checked’).val() method returns “on” when checkbox is checked and “undefined”, when checkbox is unchecked. The “:checked” selector specifically designed for radio button and checkboxes.

The below method is used to find out all the checkbox checked through out the page. When we use many checkboxes in our html, we will have to validate checkebox or find out all the checkboxes which are checked by the user. So, we will use the following method to validate checkbox or find all the checked checkboxes.

$("input[type='checkbox']:checked").each(
    	function() {
	// Your code goes here...
	}
);

label, , , , , , , ,

About the author