How to change each element of django template for loop with javascript

Viewed 30
        {% for transaction in transactions %}
            <ul>
                <li>{{transaction.number}}</li>
                <li id = "price">{{transaction.price}} USD </li>
                <li>{{transaction.created}}</li>
            </ul>
            <hr>
        {% endfor %}

I made currency converter option with api. In this case user has 3 transactions. How can i change each transaction's currency with javascript after using dropdown menu? When i change currency by document.getElementById("price").innerHTML = ${totalExchangeRate2} ${selectValue}; (it is onchange with dropdown menu) only first price changes. How to make this django loop avaible in javascript or something like this?

1 Answers

instead of your li:

<li id = "price">{{transaction.price}} USD </li> 

create it with unique id

<li id = f"price-{{transaction.pk}}">{{transaction.price}} USD </li>

from this moment each li element will have its own unique id, with which you could change it with JS

next with JS you can do something like this:

document.getElementById("price-1").innerHTML = ${totalExchangeRate1} ${selectValue}
document.getElementById("price-2").innerHTML = ${totalExchangeRate2} ${selectValue}
document.getElementById("price-3").innerHTML = ${totalExchangeRate3} ${selectValue}

it would be better done with ForEach, but this is only example

Related