Ad

The Checkbox Check If It Is Checked Does Not Work

- 1 answer

I have a problem seeing if the checkbox has been checked.

In particular, I have a table with id, name and country and an additional column with a checkbox. The purpose is to return all the ids of the checkbox that has been selected. But what I notice is that the if statement doesn't seem to work.

Can you kindly help me?

function GetSelected() {
  var table = document.getElementById(mytable);
  var rowCount = table.rows.length;
  console.log(rowCount)
  for (var i = 1; i < rowCount; i++) {
    var row = table.rows[i];
    var chkbox = table.getElementsByTagName("INPUT");
    if (chkbox[i].checked) {
      var row = checkBoxes[i].parentNode.parentNode;
      id_art += row.cells[0].innerHTML;
      console.log(id_art);
    }
  }
}
<table cellspacing="0" rules="all" border="1" id="my-table" style="border-collapse: collapse;">
  <tr>
    <th>&nbsp;</th>
    <th style="width:80px">Check</th>
    <th style="width:80px">Id</th>
    <th style="width:120px">Name</th>
    <th style="width:120px">Country</th>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>1</td>
    <td>John Hammond</td>
    <td>United States</td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>2</td>
    <td>Mudassar Khan</td>
    <td>India</td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>3</td>
    <td>Suzanne Mathews</td>
    <td>France</td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>4</td>
    <td>Robert Schidner</td>
    <td>Russia</td>
  </tr>
</table>
<br />
<input type="button" value="Get Id Selected" onclick="GetSelected()" />

Ad

Answer

You can grab all the checked checkboxes and loop over them to get the text in the next td element.

function getSelected() {
  var cbs = document.querySelectorAll('#my-table input[type="checkbox"]:checked');
  console.log(cbs.length);
  const ids = Array.from(cbs).map(cb => cb.closest('td').nextElementSibling.textContent);
  console.log(ids);
}
<table cellspacing="0" rules="all" border="1" id="my-table" style="border-collapse: collapse;">
  <tr>
    <th>&nbsp;</th>
    <th style="width:80px">Check</th>
    <th style="width:80px">Id</th>
    <th style="width:120px">Name</th>
    <th style="width:120px">Country</th>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>1</td>
    <td>John Hammond</td>
    <td>United States</td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>2</td>
    <td>Mudassar Khan</td>
    <td>India</td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>3</td>
    <td>Suzanne Mathews</td>
    <td>France</td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>4</td>
    <td>Robert Schidner</td>
    <td>Russia</td>
  </tr>
</table>
<br />
<input type="button" value="Get Id Selected" onclick="getSelected()" />

Ad
source: stackoverflow.com
Ad