VLDZ
VLDZ

Reputation: 13

Getting a checkbox from a table field

Good afternoon, below is the code in it I am getting fields from my table. The 0 field contains a checkbox, how can I find out if it is checked or not(true or false)? You need to change this line: console.log (td.item (f));

var table = document.getElementsByClassName("table-sm");
for (var i = 0; i < table.length; i++) {
  var tr = table.item(i).getElementsByTagName("tr");
  for (var j = 0; j < tr.length; j++) {
    var trr = tr.item(j);
    var td = tr.item(j).getElementsByTagName("td");

    for (var f = 0; f < td.length; f++) {
      if (f === 0) console.log(td.item(f));
      console.log(td.item(f).innerText);
    }
  }
}

   

Upvotes: 1

Views: 82

Answers (1)

Nawaf Khalifah
Nawaf Khalifah

Reputation: 786

Firstly, please learn about JavaScript Table API is much better than just making complex for-loops.

Next time please add full code (HTML/JavaScript) so people can help you.

Now let's fix your code.

Suppose we have this table

<table class="table-sm" id="myTable">
   <thead>
      <tr>
         <th>Checkbox</th>
         <th>ID</th>
         <th>Name</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td><input type="checkbox" name="selected[]" checked /></td>
         <td>1</td>
         <td>Mohammed</td>
      </tr>
      <tr>
         <td><input type="checkbox" name="selected[]" /></td>
         <td>2</td>
         <td>Ali</td>
      </tr>
   </tbody>
</table>

and we want to get the first item of each rows, and check whether the checkbox is checked or not.

We can do it easly using JS Table APIs.

  1. Get the table by it's ID.
var table = document.getElementById("myTable");
  1. Get the table rows

I use Array.from() to convert HTMLCollection to normal array, so I can use Array APIs (Like .forEach).

var rows = Array.from(table.rows);
  1. Loop into table rows, and get cells of each row.
rows.map((row) => {
  var cells = Array.from(row.cells);
  
  // TODO add logic here.
});
  1. Get the firstChild of first cell.
rows.map((row) => {
  var cells = Array.from(row.cells);

  if (Array.isArray(cells) && cells.length > 0) {
    var firstChild = cells[0].firstChild;

    console.log(firstChild.checked);
  }
});

Live Example

Upvotes: 1

Related Questions