search

Home  >  Q&A  >  body text

When I run it the button doesn't do what it should

I don't know why the button doesn't work. What I want to do is that every Pokémon that has the "stuck" box checked no longer appears when I click the button. It doesn't work. I've just started coding, and as you read this, you're probably smiling. It's all very confusing.

function showUnowned() {
  var rows = document.getElementsByTagName("tr");
  for (var i = 0; i < rows.length; i++) {
    if (rows[i].getElementsByTagName("input")[2].checked == true) {
      rows[i].style.display = "none";
    }
  }
}
<h1>My Pokemon Card Collection</h1>
<table>
  <tr>
    <th>Picture</th>
    <th>Name</th>
    <th>Pokedex Number</th>
    <th>Card</th>
    <th>Other</th>
  </tr>
  <!-- This is an example of how to add a Pokemon to the table. You can copy and paste this code for each Pokemon in your collection. -->
  <tr>
    <td><img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png"></td>
    <td>Bulbasaur</td>
    <td>1</td>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
  </tr>
  <tr>
    <td><img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/2.png"></td>
    <td>Ivysaur</td>
    <td>2</td>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
  </tr>
  <tr>
    <td><img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/3.png"></td>
    <td>Venusaur</td>
    <td>3</td>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
  </tr>
  <tr>
    <td><img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/4.png"></td>
    <td>Charmander</td>
    <td>4</td>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
  </tr>



</table>
<button onclick="showUnowned()">Show Unowned Pokemon</button>

P粉068486220P粉068486220497 days ago533

reply all(1)I'll reply

  • P粉418854048

    P粉4188540482023-09-14 09:37:21

    You are looping through the elements again (there are 4 elements, but looped 5 times), so you can edit your code to fix this:

    function showUnowned() {
      var rows = document.getElementsByTagName("tr");
      for (var i = 1; i < rows.length; i++) {
        if (rows[i].getElementsByTagName("input")[2].checked == true) {
          rows[i].style.display = "none";
        }
      }
    }
    

    reply
    0
  • Cancelreply