JQuery Toggle Checkbox

I have a problem. I am trying to toggle the checkboxes to add some css to the parent <tr>

This is what I still have

  $('input[type=checkbox]').toggle(function(){ $(this).parents('tr').addClass('selectCheckBox', 970); }, function(){ $(this).parents('tr').removeClass('selectCheckBox', 970); }); 

However, the result of this is that <tr> gets selectCheckBox , but the checkbox is not checked. So I tried the following:

  $('input[type=checkbox]').toggle(function(){ $(this).attr('checked',true); $(this).parents('tr').addClass('selectCheckBox', 970); }, function(){ $(this).attr('checked',false); $(this).parents('tr').removeClass('selectCheckBox', 970); }); 

Once again, no luck.

I believe this is due to how the checkbox id looks.

 <input type="checkbox" name="select[]" id="select[]"> 

Then I tried to exit [] using \\[\\] as I used in the past, but no luck.

Is there a way to make a checkbox ?

+4
source share
3 answers

I get it. I needed to use toggleClass along with the rest of the jQuery user interface options to get the desired effect.

 $('input[type=checkbox]').click(function(){ $(this).parents('tr').toggleClass('selectCheckBox', 1000, "easeOutSine" ); }); // Here are the parameteres below .toggleClass( className [, switch ] [, duration ] [, easing ] [, complete ] ) 
0
source

Try the change event. Also, it seems to me that the toggle event is deprecated, and addClass does not accept the second parameter (unless you use jQuery UI).

 $('input[type=checkbox]').change(function() { $(this).parents('tr').toggleClass('selectCheckBox', $(this).is(':checked')); }); 
+1
source

Perhaps there is an opportunity to optimize this a bit:

 $('input[type=checkbox]').on('click', function() { var $this = $(this); if ($this.is(':checked')) { $this.closest('tr').addClass('selectCheckbox'); } else { $this.closest('tr').removeClass('selectCheckbox'); } }); 

Jsfiddle

+1
source

All Articles