2

I am trying to toggle a checkbox between checked and un-checked using the following code, but it seems to only un-check.

var checkbox = $this.find('[name="category"]');

if ('checkbox:checked') {
    checkbox.prop("checked", false);
} else {
    checkbox.prop("checked", true);
}

How can I make it toggle correctly?

Is there a better way to do this instead of doing if/else statements? .toggle() doesn't seem to work for checkboxes correct?

7 Answers 7

2

Try Toggle function like

$('[name="category"]').toggle(
 function() { 
    $(this).find(':checkbox').prop('checked', true); },
 function() { 
    $(this).find(':checkbox').prop('checked', false);
 }); 

or

just try like this

   var checkbox = $this.find('[name="category"]'); 
   $checkbox.attr('checked', !$checkbox.attr('checked'));

or for jquery 1.6

    $checkbox.prop('checked', !$checkbox[0].checked);
Sign up to request clarification or add additional context in comments.

Comments

2

Since it appears to be only one element, just use checkbox.checked

var checkbox = $this.find('[name="category"]').get(0);

checkbox.checked = !checkbox.checked;

1 Comment

It's actually a table full of posts, so there are a lot of elements.
0

Try

 if (checkbox.is(':checked')) { ... }

or

checkbox.prop('checked', checkbox.is(':checked'));

Comments

0

Try

if (checkbox.is(':checked')) {

or, a bit more complicated:

if ($this.find('[name="category"]:checked').length) {

http://api.jquery.com/checked-selector/

http://api.jquery.com/is/

Comments

0

You need to revisit your IF statement. You are basically checking for a string 'checked:checked'

Comments

0
var checkbox = $this.find('[name="category"]');
checkbox.prop("checked", !checkbox.is(":checked") );

Comments

0

Try this:

checkbox.prop('checked', checkbox.is(':checked'));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.