Bryce Wellman
Bryce Wellman

Reputation: 23

color p tags with different colors based on for loop in Django template

I am creating an application where answers to multiple quizzes are displayed on one page.

To do this I have a for loop which loops through each one and within that loop use if tags to color the correct answer green. However, all quizzes get the same answered color, because the css style doesn't stick between each for loop.

How can i stop this?

{% for quiz in Quizes %}
    <div class="question-Card">
        <p id="a"> A:{{choice1}}
        <p id="b"> A:{{choice2}}
        <p id="c"> A:{{choice3}}
        <p id="d"> A:{{choice4}}

        {% if quiz.answer == 'a' %}
            <style>
                #a {
                color: green;
                }
            </style>
        {% endif %}

        **this then continues for the other choices 
but the code isn't the issue, so I will save you the read** 

    </div>
{% endfor %}

The issue is that if the last quiz to be 'read' is colored c then they are all colored c and it doesn't do each one individually, please help

Upvotes: 2

Views: 297

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477210

The problem is that the next question can have 'a' as answer, and since the ids are all the same, this thus means that the style will be applied to that of the next entry as well. Normally you should not give two DOM items the same id.

We can solve this by simply adding it as a style="…" attribute:

{% for quiz in Quizes %}
  <div class="question-Card">
    <p {% if quiz.answer == 'a' %}style="color:green"{% endif %}> A:{{choice1}}
    <p {% if quiz.answer == 'b' %}style="color:green"{% endif %}> A:{{choice2}}
    <p {% if quiz.answer == 'c' %}style="color:green"{% endif %}> A:{{choice3}}
    <p {% if quiz.answer == 'd' %}style="color:green"{% endif %}> A:{{choice4}}
  </div>
{% endfor %}

Upvotes: 1

Related Questions