Developing a rating system that utilizes an API to generate star ratings

My application has an API that returns a rating from 1-5 under the category "ratings." Along with this, I have a set of 5 stars. Upon clicking a button, these stars are supposed to change color based on the rating received - turning red for each number in the ratings and one star remaining black. I have created the necessary HTML and CSS elements, but upon pressing the button, no data is displayed. As a workaround, I added a basic alert which worked fine. The current implementation looks like this:

DEMO:

$("#viewreview").click(function(){
    $.ajax("api link").done(function(data){
        $(".reviewblk").html('');
        var htmlstr = '';
        for(var i=0; i<data.length; i++){
            var rating = parseInt(data[i]["rating"]);
            var chk = ['', '', '', '', ''];
            for(var j=0; j<rating && j<5;j++){
                chk[j] = 'checked';
            }
            htmlstr += '<div class="preview"><img src="reviewicon1.jpg" alt="reviewpic" class="revImg" /><div class="stars"><p class="checked '+chk[0]+'"></p><p class="checked '+chk[1]+'"></p><p class="checked '+chk[2]+'"></p><p class="checked '+chk[3]+'"></p><p class="checked '+chk[4]+'"></p></div><h3 class="personName">'+data[i]["nickname"]+'</h3><div class="revtext"><p>'+data[i]["review"]+'</p></div></div><hr />';
        }
        $(".reviewblk").html(htmlstr);
    });
})
... (CSS and HTML code snippets follow) ...

Answer №1

Take a look at the following solution.

$("#viewreview").click(function() {
  $.ajax("api link").done(function(data) {
    $(".reviewblk").html('');
    var rating, preview, stars;
    $.each(data, function(i, el) {
      preview = $("<div>", {
        class: "preview"
      }).appendTo(".reviewblk");
      $("<img>", {
        src: "reviewicon1.jpg",
        alt: "Review Icon",
        class: "revImg"
      }).appendTo(preview);
      stars = $("<div>", {
        class: "stars"
      }).appendTo(preview);
      rating = parseInt(el.rating);
      for (var i = 1; i <= 5; i++) {
        $("<p>", {
          class: (i <= rating ? "checked" : "unchecked")
        }).appendTo(stars);
      }
      $("<h3>", {
        class: "personName"
      }).html(el.nickname).appendTo(preview);
      $("<div>", {
        class: "revText"
      }).html("<p>" + el.review + "</p>").appendTo(preview);
      $("<hr>").appendTo(preview);
    });
  });
});

We can utilize jQuery to dynamically create and add elements as needed. By using $.each(), we go through each item in the data. Since there are always 5 items to 'check', we can easily generate them with a loop based on the rating. Each one that is less than or equal to the rating will be marked as 'checked' while the rest will be 'unchecked'.

For instance, if the rating is 3, the result would be:

<p class="checked"></p>
<p class="checked"></p>
<p class="checked"></p>
<p class="unchecked"></p>
<p class="unchecked"></p>

During the iteration, when i equals 1 or 2, the condition is met, so it's marked as 'checked'. When i reaches 4 or 5, they are 'unchecked' since the condition is no longer true.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using AngularJS to Send Elements to Scripts and Selectors

When I use the following template: <div id="container"> <textarea name="message"></textarea> <button value="send" ng-click="testMethod($parent)"> </div> In the JavaScript code: $scope.testMethod = function(element) ...

Using InvokeScript with a WPF browser application

Can someone explain why I'm encountering the error (Exception from HRESULT: 0x80020006 (DISP_E_UNKNOWNNAME)) when trying to call a javascript function in a WPF application (.Net 4)? The application hosts a browser control and utilizes local html file ...

Interconnected props in Material UI components interact with one another

Is there a way to have the value of one property in a Material UI component reference another property within the same component? For example, can I make the value property in a Switch component refer to the checked property? <Switch checked={sing ...

Utilizing Jquery Ajax to send a post request containing input values through Tampermonkey

I encountered an issue with my code - even though the logs in console show that it is working, I am unable to send the values to my server using AJAX post. jQ(document).on("keyup", "form input", function () { var value = jQ(this).val(); ...

Pattern to identify digits from 0 to 9 along with specific symbols

I am currently in the process of creating a regular expression that can match 0 to 9 (up to 10 digits) and /-. (0 to 2 max), without having to be all . or all //. It can be /.\- or .-. or any combination of the three, with a maximum of two of those ch ...

Encountering a 405 error when sending a post request to Flask using AJAX for form submission - could this be a CORS problem?

I'm attempting to utilize Ajax and jQuery on the client side to send a POST request from a form submission, with Flask handling the data processing on the server side. However, when I try to make the post request, I encounter a 405-method not allowed ...

contrasts in regex special characters: .net versus javascript

Here is my current javascript implementation: EscapeForRegex = function(input) { var specials = ["[", "\\", "^", "$", ".", "|", "?", "*", "+", "(", ")", "{", "}"] for (var k in specials) { var special = specials[k]; ...

Removing a MongoDB record when a URL is accessed using node.js

Currently, I am developing a Twitter replica for a project using node.js and express. Tweets are being stored in MongoDB. One of the functionalities I am working on is allowing users to delete their tweets. The idea is to have a button or link under each ...

“What could be causing the issue of newly added components not appearing on an extjs panel after removing other components?”

Using ExtJs 6 classic, I have a situation where I am dealing with an Ext.panel.Panel that contains dynamically created child Panels and containers. What I do is save references to these containers and remove them from the parent Panel (this) utilizing the ...

Closing WebSocket connection after sending data

I came across an interesting blog post titled Experimenting with Node.js and decided to try setting it up on my own using the author's provided gist. Unfortunately, I encountered some issues. After further investigation, I discovered that even though ...

When a class and ID are dynamically applied, the click event may not fire and the CSS may not be applied

Hey everyone, I am facing an issue with declaring id and class when creating a table dynamically. I have tried multiple functions to make my click event work but without success. Can anyone help me with this? Below is the code for my dynamic table where I ...

The Double Negation operator

While reading a book, I came across this code snippet: !!(document.all && document.uniqueID); I'm wondering why the double not operator is used here. Doesn't the && operator already convert the result to a Boolean? ...

Issue with custom cursor not functioning properly when hovering over hyperlinks

I'm currently developing a website and I've created a custom cursor to replace the default one. The custom cursor is detecting mouse movement, but it's not interacting with hyperlinks. Below is the code I'm using. HTML <div class=& ...

Transmitting an Ajax request via property path

I'm experiencing issues with sending data to the server. Here is my Ajax call: $.ajax({ url: config.api.url, type: config.api.method, contentType: config.api.contentType, dataType: config.api.dataType, data: config.api.dataType === ...

Utilizing fluent-ffmpeg in nodejs and express to effortlessly download a video

I've been recently tackling a side project that involves downloading videos from Reddit. The tricky part is that the video and audio are stored in separate files, requiring me to merge them before being able to download them onto the client's dev ...

Connection to Cloud9 MongoDB

Is there a way to connect to the mongoDB I have set up in my Cloud9 from an HTML document? I've successfully connected to the database from the terminal, but when I try calling the function containing this code within my script in an HTML file, it doe ...

Exploring the realm of variable scope in JavaScript and Vue.JS

I am a newcomer to JavaScript and I have encountered an issue with the scope of my object/variable. Can you please help me understand why my {endtoken:this.token} is empty, while console.log({rawToken:e.data}) is not? I find the concept of variable scope ...

Finding the nearest span value upon clicking through a specific class

Whenever a user clicks on a hyperlink, my goal is to locate the nearest span element with a specific class and retrieve the text within that class. As of now, it is only returning blank text: Here is the provided HTML code snippet: <div class="plan re ...

Issue with PHP and CSS: Navigation bar does not properly indicate the current active tab

When attempting to display a webpage with a tabbed style navbar that changes upon clicking, I am encountering an issue. The desired result is shown in this image: https://i.sstatic.net/xR9zw.png However, after clicking on the links multiple times, the ou ...

Using Express in Node.js to send a GET request to a different server from a Node route

When a client triggers a GET request by clicking a button on the index page, it sends data to a route that is configured like this: app.js var route = require('./routes/index'); var button = require('./routes/button'); app.use('/ ...