user964406
user964406

Reputation: 43

Change background colour on table cell and check checkbox

I have have a table with the class "pretty".

Each row has a checkbox next to it that selects the data using a form.

I want to be able to click the cell and have the checkbox ticked/unticked.

I have this working using

$(document).ready(function () {
  $('.pretty tr').toggle(function() {
      $(this).find(':checkbox').attr('checked', true);  
  }, function() {
      $(this).find(':checkbox').attr('checked', false);
});

});

In addition to this I want the cells background colour to change when the checkbox has been selected and unchange if its deselected.

I have not had any luck doing this, any idea's?

I have tried adding

$(this).addClass('cssclassname');

To the above with no luck :(

Edit just an update the class "pretty" already has the following css which makes the data in the table differ in colour for each row.

It seems when I try the jquery toggleClass function it doesn't apply it over the already existing CSS?

    table.pretty {
  background: whitesmoke;
  border-collapse: collapse;
}
table.pretty th, table.pretty td {
  border: 1px silver solid;
  padding: 0.2em;
}
table.pretty th {
  background: gainsboro;
  text-align: left;
}
table.pretty caption {
  margin-left: inherit;
  margin-right: inherit;
}
table.pretty tr:nth-child(odd)    { background-color:#eee; }
table.pretty tr:nth-child(even)    { background-color:#fff; }

Upvotes: 2

Views: 1990

Answers (2)

Null Pointer
Null Pointer

Reputation: 9309

See this DEMO

An alternative to your Jquery is HERE

Lets check the demo HERE . I am not sure it is the best way to do it

Upvotes: 1

genesis
genesis

Reputation: 50982

$(document).ready(function () {
  $('.pretty tr').toggle(function() {
      $(this).find(':checkbox').attr('checked', true);

  }, function() {
      $(this).find(':checkbox').attr('checked', false);
  });
});

$(this).addClass('class'); will do it...

Upvotes: 0

Related Questions