Check if a checkbox is checked with jQuery

August 02, 2014 | Last tested: June 2015 | 1116 views | Comments

Use the property of an element to test whether it has been checked or not. Either use $(elem).prop("checked"); or $(elem).is(":checked"); for testing, both returns a boolean value which is perfect for the task.

For example.

Test a check box if it is checked with a click of a button.

Requirement:

  • If it returns true, print the message "checked" to the console.

jQuery code:

$(document).ready(function(){
	$("#testButton").click(function(){
		if($("#checkbox").prop("checked")){
			console.log("checked");
		}
	});
});

HTML code:

<p>
	<input type="checkbox" id="checkbox">
	<input type="button" id="testButton" value="Test">
</p>

 

Live Demo:

Open your console to see the result.

 

More advanced usage example:

Select all possible skills.

Task:

  1. Display the selected skill when the check box is checked.
  2. Remove the skill when the check box is unchecked.

jQuery code:

$(document).ready(function(){
	$(".skill").click(function(){
		var varId = $(this).attr("id");
		var varContent = $("#skills").text();
		var varString =  "(, )?" + varId + ($("#skills").text().indexOf(varId)==0 ? "(, )?" : "");
		var varRegEx = new RegExp(varString,'i');

		if($(this).prop("checked")){
			$("#skills").append(($("#skills").text()!="" ? ", " : "") + varId);
		}
		else{
			$("#skills").html(varContent.replace(varRegEx,''));
		}
	});
});

HTML code:

<div>
<p>Select your Skills:</p>
<p>JAVA <input type="checkbox" class="skill" id="JAVA"></p>
<p>PHP <input type="checkbox" class="skill" id="PHP"></p>
<p>Javascript <input type="checkbox" class="skill" id="Javascript"></p>
<p>jQuery <input type="checkbox" class="skill" id="jQuery"></p>
<p id="skills"></p>
</div>

 

Live Demo:

Select your Skills:

JAVA

PHP

CSS

jQuery