'How to get row and column name of a selected checkbox inside a table cell using javascript

When I select a checkbox, it should give me the time (row) and day (column) value using javascript. If possible I should put these selected values into two separate arrays for time and day.

For example:



Solution 1:[1]

$("input[type=checkbox]").change(function() {
    if (this.checked) {
        let checkedCol = this.closest('tr').cells[0];
        let time = checkedCol.textContent;
        let colInd = parseInt($(this).parent().index());
        let day = $(this).closest('table').find('tr:first').find("td").eq(colInd).text();
        alert("Time : " + time + "  Day : " + day);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
  <td></td>
  <td>Mon</td>
  <td>Tue</td>
</tr>
<tr>
  <td>8-12</td>
  <td><input type="checkbox" name="" value="1"></td>
  <td><input type="checkbox" name="" value="1"></td>
</tr>
<tr>
  <td>12-17</td>
  <td><input type="checkbox" name="" value="1"></td>
  <td><input type="checkbox" name="" value="1"></td>
</tr>
</table>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mihir