0

in my code

the length of playersTeam1 is 2

players = {
    points_id: 'player-points-1',
    assists_id: 'player-assists-1',
    rebounds_id: 'player-rebounds-1',
    fouls_id: 'player-fouls-1',
    points_button: 'button-points-1',
    assists_button: 'button-assists-1',
    rebounds_button: 'button-rebounds-1',
    fouls_button: 'button-fouls-1'
 }

html

<% for(var i=0; i < players.length; i++) { %>
   <tr>
       <td>
          <%= i + 1 %>
       </td>
       <td>
          <div class="grid grid-flow-row auto-rows-max pt-3 text-xs">
            <div class="font-bold text-base">
               B. Danialian
           </div>
           <div>
              <span id=<%=players[i].points_id %>>. 
             <%=players[i].points %></span> Pts •                               
            </div>
        </td>
        <td>
           <div class="pt-4 flex justify-start">
              <button class="mr-2 px-10 py-3 bg-blue-900 rounded-lg text-xl flex justify-center text-gray-100"
                 id=<%= players[i].points_button %>>
                   ↑
              </button>

            </div>
         </td>
<% } %>

javascript

<script type="module">
  export function inc(id) {
     var g = document.getElementById(id).innerHTML;
     document.getElementById(id).innerHTML = parseInt(g) + 1;
  }

  for (var i = 0; i < playersTeam1.length; i++) {
    document.getElementById("button-points-" + i).onclick = function () {
      inc("player-points-" + i)
    }
  }
</script>

Whenever I click the button, somehow the player-points-i is equal to 2, when the playersTeam1 is 2, so the max number should be 1.

What is the reason for this? And is there a way to not have this happen?

Is there another way to create multiple onclick getElementById()s in a for loop. I need a for loop because the amount of players is dynamic depending on the team.

splurring
  • 37
  • 5

0 Answers0