mercredi 29 avril 2020

Javascript select entire row (change background color) of a table with checkbox and deselect when next checkbox is clicked

I have table where I want to select entire row (change background color). Rows are selected by a checkbox and when a next row is selected, the previous row has to deselect.

This is my table

<table id="table" border="1">
  <tr>
    <th></th>
    <th>ID</th>
    <th>Name</th>
    <th>Surname</th>
  </tr>
  <tr>
    <td class='row'>
      <input type='checkbox' class='check' onclick='markRow(0)'>
    </td>
    <td class='row'>-</td>
    <td class='row'>-</td>
    <td class='row'>-</td>
  </tr>
  <tr>
    <td class='row'>
      <input type='checkbox' class='check' onclick='markRow(1)'>       
    </td>
    <td class='row'>-</td>
    <td class='row'>-</td>
    <td class='row'>-</td>
  </tr>
  <tr>
    <td class='row'>
      <input type='checkbox' class='check' onclick='markRow(2)'>       
    </td>
    <td class='row'>-</td>
    <td class='row'>-</td>
    <td class='row'>-</td>
  </tr>
</table>
#table{
  border-collapse: collapse;
}

I named every table cell with class="row". Calculating an interval in which a specific row is positioned and using the for loop, I should be able to set background color to those table cells. Intervals are: for the first row its 0-3, second 4-7 and third 8-11.

I tried this:

var clear1 = 0;
var clear2 = 0;
//these two should clear the previous row

var counter = 0;  
//this will ensure that clearing doesn't happen the first time


//function parameter is given by this checkbox from table  
//<input type='checkbox' class='check'onclick='markRow(0)'> 
function markRow(rowNumber){  
  var row = document.getElementsByClassName('row');
  var checkboxes = document.getElementsByClassName('check');

  var interval = rowNumber*4;

  for(var i=interval;i<=interval+3;i++){
    row[i].style = "background-color: dodgerblue;";
  }
  //for example if function gets parameter rowNumber=2, then it will color the cells in interval 8-11

  counter++;
  if(counter>1){
    for(var i=clear1;i<=clear2;i++){
      row[i].style = "";
    }
    checkboxes[clear1].checked = false;
  }
  clear1 = interval;
  clear2 = interval+3;
  //these two will save the interval from the current row and next time, for loop will delete style 
  //using this interval
}

It works for the first row, but second row and third row sometimes don't check off and don't get deselected. I don't know what could be a problem.




Aucun commentaire:

Enregistrer un commentaire