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

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?
brucegustPHP DeveloperAsked:
Who is Participating?
 
Jayadev NairConnect With a Mentor Application DeveloperCommented:
And if you say the 'checked'  property is not identified then try below script

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

Open in new window

0
 
Jayadev NairApplication DeveloperCommented:
Are checking this too early? On document ready, do you expect your checkbox will be on checked state?
0
 
brucegustPHP DeveloperAuthor 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.
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
Jayadev NairApplication DeveloperCommented:
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

0
 
brucegustPHP DeveloperAuthor 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...
0
 
Jayadev NairApplication DeveloperCommented:
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

0
 
brucegustPHP DeveloperAuthor Commented:
Thank you!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.