I created a loop inside jsp which takes 10 movies from a database. Each movie is assigned a unique id (the variable elementId
) and the rating for that movie is also found(the variable userRate
).
I have a function fillRateButton
which gets elementId
and userRate
as parameters and gives that movie a specific style. I want it to run for each movie that get created as soon as it gets created. That's why I put a script tag before the end of the for loop.
<script> fillRateButton("<%=elementId %>",<%=userRate %>); </script>
The problem is that this doesn't work and I can't call my function using onload()
because the variable userRate
changes.
<%
String email = ((request.getSession()).getAttribute("emailSession")).toString();
for (int i = 0; i<10;i++){
Movie movie = GetMovie.simply();
String movieSrc ="images/movies/m" + movie.getMovieId() + ".jpg";
int userRate = UserRates.getRates(email, movie.getMovieId());
String elementId = "element"+i;
%>
<div class="w3-row-padding w3-white w3-border w3-padding">
<div class="w3-col s5">
<div style="width:100%;height:200px">
<img src="<%= movieSrc %>" alt="<%=movie.getMovieName() %>" class="w3-border w3-round " style="width:100%;height:100%">
</div>
<!-- Rate the movie -->
<div class= "w3-container w3-teal w3-padding-left" id="<%=elementId %>">
<span class="fa fa-heart w3-hover-text-pink w3-xlarge rateButton" style="cursor:pointer;color:white;" onClick="addFill(this,2);addRating(2,<%=movie.getMovieId() %>)"></span>
<span class="fa fa-thumbs-up w3-hover-text-blue w3-xlarge rateButton" style="cursor:pointer;color:white;" onClick="addFill(this,1);addRating(1,<%= movie.getMovieId() %>)"></span>
<span class="fa fa-thumbs-down w3-hover-text-black w3-xlarge rateButton" style="cursor:pointer;color:white;" onClick="addFill(this,0);addRating(0,<%= movie.getMovieId() %>)"></span>
</div>
<script> fillRateButton("<%=elementId %>",<%=userRate %>); </script>
<%} %> <!-- End of the for loop -->
my javascript function which is located just before closing body element
const fillRateButton = (element , rate)=>{
let rateMenu = document.getElementById(element);
let list = rateMenu.getElementsByClassName("rateButton");
if (rate===2)
list[0].style.color = "#ff1a40";
else if (rate===1)
list[1].style.color = "blue";
else if (rate===0)
list[2].style.color = "black";
};
I am not familiar with the jQuery library so if you answer in plain JavaScript I'd appreciate it.