When I display a list of cards using a for loop and click on them, I want to toggle some text. The issue I'm facing is that it works fine for the top card, but when I click on the card below, it toggles the text of the first card instead. This is despite giving each card a different ID in the JavaScript toggle function.
Does anyone have any suggestions on what I might be doing wrong?
<!-- HTML -->
{% for card in cards %}
<div class="card mb-3">
<div class="card-header">
<img class = "float:left mr-2 mt-1 small-profile-picture" src ="{{ card.creator.profile.image.url }}" >
<a class="mb-4 float-up" > {{ card.creator }}</a>
<small> <p class=mt-2> {{ card.date }} </p> </small>
</div> <!-- Card Header ender -->
<!-- Here we have the questions and answers -->
<div onclick="myFunction()" style="cursor: pointer;">
<div class="card-body mt-4">
<h5 class="card-title"> <a class="article-title">{{ card.question }}</a></h5>
<p id="myDIV{{card.card_id}}"> Click to see Answer </p>
<!-- <p class="card-text"> {{ card.answer}} </p> -->
</div> <!-- Card body ender -->
</div>
<!--Javascript -->
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("myDIV{{card.card_id}}");
if (x.innerHTML === "Click to see Answer") {
x.innerHTML = "{{card.answer}}";
} else {
x.innerHTML = "Click to see Answer";
}
}
</script>
{% endfor %}
Appreciate you taking the time to read this