Shirish Shirish - 29 days ago 5
Javascript Question

JQuery: Change the color of the row inside a table based on the checkbox click

I have a

table
that has huge set of data.
Now what i want to do is when user will uncheck the checkbox of that specific row, i want to change the color to grey.
What i have done till now:

$('tr').click(function () {
if(this.style.background == "" || this.style.background =="white") {
$(this).css('background', 'grey');
}
else {
$(this).css('background', 'white');
}
});

$(".uncheck").change(function(){
alert("cehc");
var ischecked= $(this).is(':checked');
alert(ischecked);
if(!ischecked){
$(this).css('background', 'grey');
}
else{
$(this).css('background', 'white');
}
});


The above functions i have written that work properly individually though. Its like
The first function will work when i click on row and second function puts an alert on unchecking the checkbox but does not change the color to grey.

How to identify if a specific checkbox has been unchecked on a row of a table and change that row color to grey?

Answer

Try using single function and use css classes for that:

$(document).ready(function() {
  $('tr').click(function() {
    var inp = $(this).find('.check');
    var tr = $(this).closest('tr');
    inp.prop('checked', !inp.is(':checked'))

    tr.toggleClass('isChecked', inp.is(':checked'));
  });

  // do nothing when clicking on checkbox, but bubble up to tr
  $('.check').click(function(e) {
    e.preventDefault();
  })
})
.isChecked {
  background-color: grey;
}
table {
  width: 100%;
  border-collapse: collapse;
}
tr {
  background-color: #fafafa;
}
/* click-through element */
.check {
  pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="checkbox" class="check">
    </td>
    <td></td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" class="check">
    </td>
    <td></td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" class="check">
    </td>
    <td></td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" class="check">
    </td>
    <td></td>
  </tr>
</table>