Jason Huang
Jason Huang

Reputation: 55

How to toggle the checkbox while the user clicks on the row where the checkbox resides in?

I have a table with 2 columns, the first column shows the text, and the other column has a checkbox.

The code is as follows, and the checkboxes are generaged by JavaScript, e.g. var checkbox = document.createElement("input");

<script type="text/javascript">
      function create_table() {
       var data = ["Sandwidch", "Hamburger", "Bacon"];
       var table = document.getElementById("menu");
       for (var option in data) {
          var row = table.insertRow(-1);
          var cell1 = row.insertCell(0);
          cell1.innerHTML = data[option];

          var cell2 = row.insertCell(1);
          var checkbox = document.createElement("input");
          checkbox.type = "checkbox";
          checkbox.name = "choiceCbx";
          cell2.appendChild(checkbox);
        }
      }
      window.onload = create_table;
</script>

<body>
    <table id="menu">
        <tr>
           <th>Food</th>
           <th>Choice</th>
        </tr>
    </table>
</body>

When the user clicks on one of the rows in the table, if the checkbox on the row was checked, it should become unchecked, and vice versa.

I used the following code to toggle the checkbox but in vain, it seems just detects the "TH" row, but not the "TR" rows:

$(document).ready(function() {
  $('#menu tr').click(function(event) {
    if (event.target.type !== 'checkbox') {
      $(':checkbox', this).trigger('click');
    }
  });
});

How should I modify my code to make the toggle function work?

Upvotes: 2

Views: 915

Answers (2)

antnewbee
antnewbee

Reputation: 1949

Try this. Also you might want to add more details to your question because the HTML does not contain any checkboxes

https://forum.jquery.com/topic/toggle-checkboxes-in-a-table-after-click-function

Upvotes: 0

Mister Jojo
Mister Jojo

Reputation: 22320

you can do that...

const table_foods = document.querySelector('#records tbody')

table_foods.onclick=e=>
  {
  if (e.target.matches('input[type=checkbox]')) return  // to not disturb  natural check action
  let chkBx = e.target.closest('tr').querySelector('input[type=checkbox]')
  chkBx.checked = !chkBx.checked  
  }
 /* cosmetic part */

table {
  border-collapse: collapse;
  margin-top: 25px;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 14px;
  } 
thead {
  background-color: aquamarine;
  }
tbody {
  background-color: #b4c5d8;
}
td, th {
  border: 1px solid grey;
  padding: .3em .7em;
}
<table id="records" class="content">
  <thead>
    <tr> <th>Food</th> <th>Choice</th> </tr>
  </thead>
  <tbody>
    <tr>
      <td>Sandwitch</td>
      <td><input type="checkbox" name="answerCbx-1" /></td>
    </tr>
    <tr>
      <td>pizza</td>
      <td><input type="checkbox" name="answerCbx-2" /></td>
    </tr>
  </tbody>
</table>

Upvotes: 3

Related Questions