6

So I have an issue. I'm trying to toggle checkboxes in order to add some css to the parent <tr>

This is what I have so far

 $('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 the <tr> does receieve the selectCheckBox but the checkbox does not become 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 it has to do with how the checkbox id looks.

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

I then tried escaping the [] by using \\[\\] as I've used in the past, but no luck.

Is there a way to make the checkbox checked?

Dimitri
  • 1,906
  • 3
  • 25
  • 49

3 Answers3

3

Try on change event. Also as I think toggle event is deprecated and addClass doesn't take a second parameter (unless you're using jQuery UI).

$('input[type=checkbox]').change(function() {
  $(this).parents('tr').toggleClass('selectCheckBox', $(this).is(':checked'));
});
elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • Awesome!! This worked perfectly. I thought of the change event, but didn't think it'd work! THe addClass has the second parameter to ease in the effect of the class. it fades it in. – Dimitri Dec 19 '12 at 00:55
1

There may be a way to optimize this a bit more:

$('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

Syon
  • 1,604
  • 13
  • 16
0

I figured it out. I needed to use toggleClass along with the rest of jQuery UI parameters to get the effect needed.

$('input[type=checkbox]').click(function(){
    $(this).parents('tr').toggleClass('selectCheckBox',  1000, "easeOutSine" );
});

// Here are the parameteres below
    .toggleClass( className [, switch ] [, duration ] [, easing ] [, complete ] )
Dimitri
  • 1,906
  • 3
  • 25
  • 49