i woud like to show star based on rating . i can only show one product with rating stars and the other products don't show any star only show rating number. could help to check which part need to change ?
<%- include ('_layouts/header'); -%>
<h1>......Exciting Books.....</h1>
<hr size="100" width="100%" align="center" color="black">
<br>
<div >
<% savedexcit.forEach(function(products){ %>
<div >
<a href="/products/<%= products.category %>/<%= products.slug %>">
<img src="/product_images/<%= products.id %>/<%= products.image %>" alt="">
</a>
<h3><%= products.title %></h3>
<b>Rating: <span id=stars></span><%= products.rating %>/5</b>
<a href="/products/<%= products.category %>/<%= products.slug %>">View Details</a>
</div>
<% }); %>
</div>
<script>
<% savedexcit.forEach(function(products){ %>
document.getElementById("stars").innerHTML = getStars(<%= products.rating %>);
function getStars(rating) {
// Round to nearest half
rating = Math.round(rating * 2) / 2;
let output = [];
// Append all the filled whole stars
for (var i = rating; i >= 1; i--)
output.push('<i aria-hidden="true" style="color: gold;"></i> ');
// If there is a half a star, append it
if (i == .5) output.push('<i aria-hidden="true" style="color: gold;"></i> ');
// Fill the empty stars
for (let i = (5 - rating); i >= 1; i--)
output.push('<i aria-hidden="true" style="color: gold;"></i> ');
return output.join('');
}
<% }); %>
</script>
<%- include ('_layouts/footer'); -%>
CodePudding user response:
you can use jquery library:
https://www.jqueryscript.net/other/rating-star-icons.html
<div id="dataReadonlyReview"
data-rating-stars="5"
data-rating-readonly="true"
data-rating-value="3"
data-rating-input="#dataReadonlyInput">
and you can see : Turn a number into star rating display using jQuery and CSS
CodePudding user response:
Id in html is used for identifying individual element and Checking your code there are two places where ID is wrongly declared, that is you are declaring it multiple times.
In the Creation section for row
<h3><%= products.title %></h3> <b>Rating: <span id=stars></span><%= products.rating %>/5</b>In the script tag where you are accessing id
<% savedexcit.forEach(function(products){ %> document.getElementById("stars").innerHTML = getStars(<%= products.rating %>);
To solve this issue you either need to add different ids, which you can do simply by adding a counter to it or you need to add a class on the star and use it to access the elements or just access it by using class.
var stars = document.querySelectorAll(".star");
for (var i = 0; i < stars.length; i ) { // or use a forEach
... operation you need to perform ..
}
CodePudding user response:
When you get
document.getElementById("stars")
it is always refered to the first element. The possible solution is to set proper id to each element

