3cool4school
3cool4school

Reputation: 15

Targeting checkboxes within a table

I have a table in which I am trying to use jquery to target checkboxes. I want to click a checkbox within an individual td and then change that td's background color, but I can't seem to target the checkboxes at all. this is the tr of my table (it has more td's I just included two for this error.

<tr class="sources">
  <td><a href="#">Single Life Annuity</a></td>
  <td>
    <div class="left"><input type="checkbox"></div>
    <div class="right">
      <span class="relval">100%</span>
      <span class="benyou">$517.00</span>
      <span class="benben">$0</span>
    </div>
  </td>
  <td>
    <div class="left"><input type="checkbox"></div>
    <div class="right">
      <span class="relval">98%</span>
      <span class="benyou">$2,916.00</span>
      <span class="benben">$0</span>
    </div>
  </td>
</tr>

This is the jquery I am using to find the checkbox's. I am using a console.log to make sure I have found the checkbox but in essence would use addClass(".active");

 $(".sources td").click(function(e)
 {
   $(this).parent().find('input:checkbox').attr('checked', 'checked');
   console.log('you got it!');
 });

Any help would be great!! Thanks in advance.

Upvotes: 0

Views: 99

Answers (4)

IT ppl
IT ppl

Reputation: 2647

As required : DEMO

$('input[type="checkbox"]').click(function() {
    if($(this).is(':checked')) {
        $(this).parent().parent().css('background','red');
    } else {
       $(this).parent().parent().css('background','white');
    }
});

Other way, works by clicking anywhere in <td> : DEMO

$(".sources td").click(function (e) {
    if ($(this).find('input:checkbox').is(':checked')) { 
        $(this).find('input:checkbox').attr('checked', false);
        $(this).closest('td').css('background','white');
    }
    else
    {
        $(this).find('input:checkbox').prop('checked', 'checked');
        $(this).closest('td').css('background','red');
    }
});

Upvotes: 0

DotNetWala
DotNetWala

Reputation: 6610

You can also try using the .prop() method.

 $(this).parent().find('input:checkbox').prop("checked", true);

http://api.jquery.com/prop/

Upvotes: 0

tuffkid
tuffkid

Reputation: 1323

$('input[type="checkbox"]').click(function() {
    if($(this).is(':checked')) {
        $(this).parent().parent().addClass('active');
    } else {
        $(this).parent().parent().removeClass('active');
    }
});

Upvotes: 1

j08691
j08691

Reputation: 207901

Using your example (which is bound to clicks on the table cell), this would select the cell and apply a red background to it:

$(this).css('background','red');

jsFiddle example

If you'd rather bind to the click event of the checkbox, try this:

$(".sources td input").click(function (e) {
    $(this).parent().find('input:checkbox').attr('checked', 'checked');
     $(this).closest('td').css('background','red');
    console.log('you got it!');
});

jsFiddle example

Upvotes: 1

Related Questions