-6

On my current project i am creating a search function that dynamically updates the content as users select different search criteria. As my title states i want to know whether a user has check or unchecked a particular item so that my JavaScript code can appropriately adjust the content.

Using jQuery i can easily tell if someone has hit the checkbox, but I don't know how to tell whether it is or isn't checked?

example:

<label class="checkbox"><input type="checkbox" id="checkbox1"> Any in Manhattan</label> 

User clicks on it and i would like my jquery to do something like:

  $( "#checkbox1" ).on( "click", function( event, ui ){
    if("#checkbox1" === "clicked"){console.log("check it out!");}

  });
Andrew Font
  • 1,245
  • 3
  • 19
  • 38
  • Duplicate [Question 901712](http://stackoverflow.com/questions/901712/check-checkbox-checked-property-using-jquery) – Vigrant Sep 06 '13 at 19:21
  • show this portion of your code `Using jQuery i can easily tell if someone has hit the checkbox` – wirey00 Sep 06 '13 at 19:31

2 Answers2

3

You can use is:

$("#myCheckbox").is(":checked")

Which will return true if at least one item in the set is checked. In this case the set would be the (hopefully) singular element with the id myCheckbox.

Doug Morrow
  • 1,306
  • 1
  • 10
  • 18
1

Use the .checked property of the checkbox object rather than just detecting that it was clicked. As you have pointed out, just a click alone doesn't mean that it is checked because they might have clicked to uncheck it just as likely as they might have clicked to check it.

If you show us the related parts of your code we can tell you precisely how to do this in the context of your program. (For instance, you mentioned that you "can easily tell if someone has hit the checkbox." So if you put that part of your code into your question, we can show you how not only to tell if the checkbox is "hit" but also to tell if it is checked, using either the native .checked property or a jQuery selector.)

Using your code example, we can do this:

  $( "#checkbox1" ).on( "change", function( event, ui ){
    if(this.checked){console.log("check it out!");}

  });

It is better to use change instead of click for various reasons.

Update: there is more discussion here: jQuery checkbox checked state changed event

Update 2: Working JS Fiddle with the above code snippet: http://jsfiddle.net/cookies/NDjCT/

Community
  • 1
  • 1
Joseph Myers
  • 6,434
  • 27
  • 36