I want to reveal the score of one line in the table onclick.
Now it only hides and shows the first score. Is there any way that I can make it so when I press the button it doesn't reveal all the scores. Thanks! Here is what I tried:
HTML:
<table>
{% for i in games %}
<tbody>
<tr>
<td> {{i['homeTeam']}} </td>
<td style="display: none;" id="score"> {{i['homeTeamScore']}} - {{i['awayTeamScore']}} </td>
<td> {{i['awayTeam']}} </td>
<td><button onclick="displayScore()">Reveal score</button></td>
</tr>
</tbody>
{% endfor %}
</table>
Javascript:
function displayScore() {
var x = document.getElementById("score");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
CodePudding user response:
- ids have to be unique. In your code you are using the same id on multiple elements (multiple tds). You can use the loop index to make your ids unique. Try something like this
<td style="display: none;" id="score_{{loop.index}}"> {{i['homeTeamScore']}} - {{i['awayTeamScore']}} </td>
This will then give you something like score_1, score_2, etc
- Add a data-attribute to each button so that you can identify which button was clicked. Also remove the
onclick
code you have on each button (we will replace it with an event listener. Something like
<td><button data-index="{{loop.index}}">Reveal score</button></td>
Now add an on click event listener to the table body. Since each button is inside a table row which is also inside the table body, clicking the button will cause the event to 'bubble' up to the table body which will trigger the listener you have attached to the table body.
The event listener is attached to the table body and not directly to the buttons because your buttons are dynamically generated i.e. the buttons are being added at runtime (after your javascript code already exists) which means the system is not aware of those buttons.
document.querySelector("tbody").onclick = function(e){
// Find out which elem which was clicked
const clicked_elem = e.target;
// If this clicked elem is a button, then execute our code
if (clicked_elem.tagName == "BUTTON"){
// First identify which button was clicked
const index = clicked_elem.dataset.index
// Now get the td corresponding to that button
var x = document.getElementById("score_" index);
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
}