I've got a fantasy football project that I built in Django that generates a list of HTML elements. Like this...
<tbody id="page1">
{% for q in QBpage %}
<tr>
<td><h6 id="qbname">{{ q.player_name }}</h6></td>
<td><button onclick="selectPlayer()" type="button" id="qbackbutton" class="btn btn-success btn-sm m-0 waves-effect" data-player-name="{{ q.player_name }}" data-position="{{ q.position }}">Add</button></td>
<td><h6> {{ q.team }} </h6></td>
<td><h6> {{ q.position }} </h6></td>
<td><h6>{{ q.points }}</h6></td>
</tr>
{% endfor %}
</tbody>
It's a list of players (all quarterbacks) pulled from an API. What I'm trying to do is from each player's corresponding "Add" button, is add that player's name to a form field that's also on the same page. I can do that using this JavaScript function...
function selectPlayer (){
let d = document.getElementById("qbname");
document.getElementById("QB_name").value = document.getElementById("qbname").innerHTML;
}
Problem is though, I can only get the name of the first player in the list because all players end up with the same id. Therefore, you can only retrieve the first element. Even if I click on a player further down the list, that first player's name is the only one that is returned. Assigning a class won't work because, as far as I understand, you can only "getElementsByClass" so you end up retrieving all the members in the list instead of just one.
How would I go about solving this? I'm pretty sure I'm completely overthinking it and there's a simple solution that I'm just not seeing due to frying my brain on this for ages. Any advice is appreciated.