March 7, 2013

.is(':checked') returns always true

Question by artworkad シ

HTML:

<table id="list">
   <tr>
      <td><input type="checkbox" checked="true"></td>
      <td>...</td>
   </tr>
   <tr>
      <td><input type="checkbox" checked="true"></td>
      ...
   </tr>
   ...
</table>

JS:

$('#list tr').each(function(){
   console.log(
        $(this).find('input[type="checkbox"]').is(':checked')
   );    
});

Problem: the above log statement always returns true. Each tr holds some data and I want to perform an action using this data. But the user can deselect some entities which in this case is not possible because is(':checked') always returns true, even if the entry is deselected/unchecked.

Any ideas how to fix this?

Answer by Starx

Your ‘checked’ attribute has true as its value, so it will return true as even having <input type="checkbox" checked /> will also going be checked.

I created a demo with your code, with additional function to retrieve .is(":checked") as it’s property changed.

$("input").change(function() {
    console.log($(this).is(':checked'));
});

And It shows the change. Your problem must be somewhere else.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!