Home > database >  How to pass array index with HTML onclick event
How to pass array index with HTML onclick event

Time:09-13

This function takes an argument (an object containing containing the player's attributes)

const yourTeam = [];

function selectingYourTeam(player) {
  yourTeam.push(player);
  alert(yourTeam[0].name);
  return;
}

This for loop creates an HTML table, that contains all the players you can select from.

for (i = 0; i < playerPool.length; i  ) {
  document.write('<tr><td>'   playerPool[i].name   '</td><td>'   playerPool[i].region   
  '</td><td>'   playerPool[i].skills["Offence"]   '</td><td>'     
  playerPool[i].skills["Defence"]
    '</td><td>'   playerPool[i].playerID   '</td><td><button type="button"
  onclick="selectingYourTeam(playerPool[0])">Select Player</button></td></tr>');
}   

The problem is that when onclick receives i the alert()returns undefined. However, it works as expected when I give it [0], so I know that logic is working. Regardless, it must receive i in order for it to be purposeful.

<button type="button" onclick="selectingYourTeam(playerPool[0])">Select Player</button>

CodePudding user response:

What was wrong with

'<button type="button" onclick="selectingYourTeam('   playerPool[i]   ')">Select Player</button>'

is you were putting the object inside the string, instead of the value of i only.
That problably was ending like

<button type="button" onclick="selectingYourTeam(Object[object])">Select Player</button>

So go with this:

'<button type="button" onclick="selectingYourTeam(playerPool['   i   '])">Select Player</button>'

Or using template litterals (which I suggest you to explore) that would be:

document.write(`
<tr><td>
  ${playerPool[i].name}
</td><td>
  ${playerPool[i].region}
</td><td>
  ${playerPool[i].skills["Offence"]}
</td><td>
  ${playerPool[i].skills["Defence"]}
</td><td>
  ${playerPool[i].playerID}
</td><td>
  <button type="button" onclick="selectingYourTeam(playerPool[${i}])">Select Player</button>
</td></tr>`);
  • Related