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

Bruce Gust
Bruce Gust used Ask the Experts™
on
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

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Jayadev NairApplication Developer

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 NairApplication Developer

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

Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

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 NairApplication Developer

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

Application Developer
Commented:
And if you say the 'checked'  property is not identified then try below script

if ($("#spouse_check").is(":checked")) {
  //alert
}

Open in new window

Bruce GustPHP Developer

Author

Commented:
Thank you!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial