Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Uncaught TypeError: Cannot read properties of undefined (reading 'type')

I have a table with two columns: values and checkboxes. I want to identify the smallest value with a checked checkbox. I adapted the setup from this question, but changed the way I identify checkboxes from
document.getElementsByTagName('input')
to
querySelectorAll(".myCheckbox"). The initial way became a problem when I added an additional input field (which is why I included it below)

However, the function throws Uncaught TypeError: Cannot read properties of undefined (reading 'type').

What’s going wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function smallestWeight() {
  let values = [];
  const ele = document.querySelectorAll(".myCheckbox");
  let table = document.getElementById("myTable");
  let trs = table.getElementsByTagName("tr");
  for (i = 0, len = trs.length; i < len; i++) {
    if (ele[i].type == 'checkbox' && ele[i].checked == true) {
      values.push(parseFloat(trs[i].cells[0].innerHTML));
    }
  }
}


const btn = document.getElementById("click");
btn.addEventListener("click", function() {
  smallestWeight();
})
<table id="myTable">
  <thead>
    <tr>
      <th>value</th>
      <th>include</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1.1</td>
      <td><input type="checkbox" class="myCheckbox" id="include" value="include" checked></td>
    </tr>
    <tr>
      <td>2.2</td>
      <td><input type="checkbox" class="myCheckbox" id="include" value="include" checked></td>
    </tr>
    <tr>
      <td>3.3</td>
      <td><input type="checkbox" class="myCheckbox" id="include" value="include" checked></td>
    </tr>
    <tr>
      <td>4.4</td>
      <td><input type="checkbox" class="myCheckbox" id="include" value="include" checked></td>
    </tr>
  </tbody>
</table>

<button id="click">Click</button><br>
<input type="number">

>Solution :

Your code looks at all rows in the table. You do not take into account that the first row of the table is the thead. So your table rows is one more greater than the checkboxes.

const trs = table.querySelectorAll("tbody tr");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading