Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
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);
    }
  }
}

   

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!