I am currently working with Django and Jquery, I need to show some hotels with the stars rated in orange based on the average obtained from a score and the number of people who have voted for that hotel. I'll give an example
score = 8
vote= 2
overage = 4
Therefore I need to display 4 orange stars and 1 black. I have this code, but it only works for the first hotel and there are many, so I use a for.
{% for hotel in hotels %}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous"/>
<div >
<span id="1star" ></span>
<span id="2star" ></span>
<span id="3star" ></span>
<span id="4star" ></span>
<span id="5star" ></span>
</div>
<script type="text/javascript" src="{% static 'js/jquery.js' %}"></script>
<script type="text/javascript">
$(document).ready(function () {
let score = '{{hotel.score}}'
let vote = '{{hotel.vote}}'
let overage = (parseInt(score)/ parseInt(vote))
let star = document.getElementById('star')
for(let i = 0; i < overage; i ) {
document.getElementById((i 1) 'star').style.color='orange'
}
});
</script>
{% endfor%}
I don't know much Js. I'm looking forward you can healp me please.
CodePudding user response:
All your stars have the same set of IDs so it's only hitting the first it encounters. IDs should be unique. You can make them unique by including django's forloop.counter. IDs should not start with numbers so I'll change that too.
<span id="star_{{forloop.counter}}_1" ></span>
<span id="star_{{forloop.counter}}_2" ></span>
Then you can tweak your function
$(document).ready(function () {
let score = '{{hotel.score}}'
let vote = '{{hotel.vote}}'
let overage = (parseInt(score)/ parseInt(vote))
let star = document.getElementById('star')
for(let i = 0; i < overage; i ) {
document.getElementById("star_{{forloop.counter}}_" (i 1) ).style.color='orange'
}
});