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

Time:11-10

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?

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">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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");
  • Related