We help IT Professionals succeed at work.

How can I check the "checked" status of a checkbox in JQuery?

Bruce Gust
Bruce Gust asked
on
153 Views
Last Modified: 2017-12-04
I've been at this for a while to no avail.

Seems like this should be easy...

Here's what I'm doing:

<!DOCTYPE html>
<html lang="en">
<head>
<title>JQuery Example</title>
<link href="css/stylesheet.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
</head>

<body>

Spouse <input type="checkbox" id="spouse_check">

<script>
$(document).ready(function() {

	var $checkbox=$('input[id="spouse_check"]');
	if($checkbox).prop('checked'))
	{
		alert("hello");
	}
	
});

</script>
</body>
</html>

Open in new window


Doesn't work. what am I missing?
Comment
Watch Question

Jayadev NairSr.Software Engineer

Commented:
Are checking this too early? On document ready, do you expect your checkbox will be on checked state?
Bruce GustPHP Developer

Author

Commented:
No. I'm looking for something that will check to see if it's checked after the DOM  has loaded and the user has checked the box.
Jayadev NairSr.Software Engineer

Commented:
So the event you have placed the script is where gone wrong. Register the same in any event that you might want to check, usually at a submit button click as shown below

$("#btnSubmit").button().click(function(){
        var $checkbox=$('input[id="spouse_check"]');
	if($checkbox).prop('checked'))
	{
		alert("hello");
	}
    }); 

Open in new window

Bruce GustPHP Developer

Author

Commented:
I see.

But what about this: https://medium.com/js-dojo/check-if-a-checkbox-is-checked-with-jquery-2843f97d4954

It doesn't seem like he's using a "submit" dynamic. It's all happening when the user clicks on the checkbox. How is he doing that?

I couldn't get it to work...
Jayadev NairSr.Software Engineer

Commented:
If you cant figure out the event, and if you need this on form submit, try this -

$(document).on('submit','formId',function(){
   // code
});

Open in new window


or

 
$("#formid").on("submit", function(){
   //code
   return true;
 })

Open in new window

Sr.Software Engineer
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Bruce GustPHP Developer

Author

Commented:
Thank you!
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.