Displaying star ratings from a JSON file using pure JavaScript, no need for jQuery!

Currently, I am attempting to utilize JavaScript to extract data from my JSON file and display the hotel2show.rating as star ratings. The representation of stars will be based on the values provided in 'hotels.json'

Below is the JavaScript code:

function getHotels(i){

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
    if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
                hotel=JSON.parse(xhr.responseText);
                var hotel2show = hotel.hotels[i];
                document.getElementById("img-container").innerHTML = 
                "<img src='"+hotel2show.imgUrl+"'>"+
         "<p id='name'><strong>"+ hotel2show.name +"</strong></p>" +"<br/>" + "<p id='rating'><strong>"+ hotel2show.rating +"</strong></p>" +"<br/>" + "<br/>" +"<p id='price'><strong>"+ '&pound;' +hotel2show.price +
             "</strong></p>" + "<p id='text'><strong>"+ 'Total hotel stay' +"</strong></p>";

        } else {
                alert("There has been an error with the server");

        }
    } 
};
xhr.open("GET",'hotels.json', true);
xhr.send();

Moreover, here is the accompanying HTML:

<div class="container">
 <div id="lista">
  <ul> 
   <button onclick="getHotels(0)">Hotel Sunny Palms</button>
   <button onclick="getHotels(1)">Hotel Snowy Mountains</button>
   <button onclick="getHotels(2)">Hotel Windy Sails</button>
   <button onclick="getHotels(3)">Hotel Middle Of Nowhere</button>
  </ul>
</div>
<div class="banner-section" id="img-container">
</div>

Lastly, the content of my hotels.json file:

"hotels": [
    {
        "name": "Hotel Sunny Palms",
        "imgUrl": "imgs/sunny.jpg",
        "rating": 5,
        "price": 108.00
    },
    {
        "name": "Hotel Snowy Mountains",
        "imgUrl": "imgs/snowy.jpg",
        "rating": 4,
        "price": 120.00
    },
    {
        "name": "Hotel Windy Sails",
        "imgUrl": "imgs/windy.jpg",
        "rating": 3,
        "price": 110.00
    },
    {
        "name": "Hotel Middle of Nowhere",
        "imgUrl": "imgs/nowhere.jpg",
        "rating": 4,
        "price": 199.00
    }
]

If anyone has any guidance or suggestions, it would be greatly appreciated.

Answer №1

For instance, if you are using a UTF-8 charset, everything should work smoothly. The important thing to remember is the createElement function, which allows you to customize your DOM structure as needed.

var hotels = [{
  "name": "Hotel Sunny Palms",
  "imgUrl": "imgs/sunny.jpg",
  "rating": 5,
  "price": 108.00
}, {
  "name": "Hotel Snowy Mountains",
  "imgUrl": "imgs/snowy.jpg",
  "rating": 4,
  "price": 120.00
}, {
  "name": "Hotel Windy Sails",
  "imgUrl": "imgs/windy.jpg",
  "rating": 3,
  "price": 110.00
}, {
  "name": "Hotel Middle of Nowhere",
  "imgUrl": "imgs/nowhere.jpg",
  "rating": 4,
  "price": 199.00
}];

buildRating(hotels);

function buildRating(data) {
  data.forEach(function(v) {
    createRatingElement(v.rating);
  });
}

function createRatingElement(numberOfStars) {
  var wrapper = document.createElement('div');
  for (var i = 1; i <= 5; i++) {
    var span = document.createElement('span')
    span.innerHTML = (i <= numberOfStars ? '★' : '☆');
    span.className = (i <= numberOfStars ? 'high' : '');
    wrapper.appendChild(span);
  }
  document.getElementById('img-container').appendChild(wrapper);
}
span {
  display: inline-block;
  position: relative;
  width: 1.2em;
  height: 1.2em;
  color: black;
}
.high {
  color: rgb(217, 211, 0);
}
<div class="banner-section" id="img-container">

</div>

Furthermore, check out the code snippet on jsfiddle: https://jsfiddle.net/md4708oq/

Answer №2

Assuming you are familiar with extracting your ratings data, right? If you only need to display single star values (whole numbers), you can add a class to a span element and style it using CSS to change the background image accordingly.

This approach allows you to represent 1-5 stars with just 4 different images.

While not the most elegant or scalable solution, it does get the job done for this particular scenario.

First of all, let's work on cleaning up this code a bit, shall we?

var appendString = [];
appendString[0] = "<img src='" + hotel2show.imgUrl + "'>";
appendString[1] = "<p id='name'><strong>" + hotel2show.name + "</strong></p><br/>";
switch(hotel2show.rating):
case(1):
appendString[2] = "<p id='rating' class='rating-1'><strong>";
break;
case(2):
appendStirng[2] = "<p id='rating' class='rating-2><strong>";
break;
//etc 

appendString[3] = hotel2show.rating + "</strong></p>";
appendString[4] = "<br/><br/>";
appendString[5] = "<p id='price'><strong>'&pound;'" + hotel2show.price + "</strong></p>";
appendString[6] = "<p id='text'><strong>" + 'Total hotel stay' + "</strong></p>";
document.getElementById("img-container").innerHTML = appendString.join(' ');

Please note that the syntax of the switch statement may be incorrect.

Answer №3

To fetch JSON data, AJAX calls are necessary. Then, you can utilize pure JavaScript to interpret the JSON information and update your HTML content as needed. If this aligns with what you need assistance with, feel free to reach out for further guidance.

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

The result of JWT.decode may be null

I am facing an issue with decoding a JSON web token as it is returning null. I have even tried setting complete set to true, but unfortunately it still fails. The function used for generating the token is: import jwt from 'jsonwebtoken'; jwt.s ...

Looking to streamline a JavaScript function, while also incorporating jQuery techniques

I've got this lengthy function for uploading photos using hidden iFrames, and while it does the job well, it's quite messy. I'm looking to simplify it into a cleaner function with fewer lines of code for easier maintenance. function simplif ...

Calling a JavaScript function using string parameters

Lately, I've stumbled upon an issue when attempting to execute a function with multiple arguments. <button type = "button" id = "clickmepls" onclick = killButton("clickmepls", "grave1")> Click me please </button> The definition of the fu ...

Using regular expressions to replace text within brackets that have the same type of bracket in between

I am facing an issue with replacing the given string \section{Welcome to $\mathbb{R}^n$} Some content with <h1>Welcome to $\mathbb{R}^n$</h1> Some content The challenge lies in having opening { and } between the curly brackets ...

Ways to maintain the value of req.session using express-session

Check out these lines of code: const session = require('express-session'); const sessionConfig = { secret: 'somesecretkey', cookie: {secure: false}, resave: false, saveUninitialized: false, store: new mongostore({ mo ...

Use a jq shell script to extract a specific field and generate statistical data

I am looking to tally the number of "domains" where the value of "adminLock" is set to 1. Below is the structure of my JSON data: { "code": 0, "message": "Success", "data": { "recordCount": "128", "pageSize": 100, "page": 1, "pageCou ...

Is it possible to define a variable within a JavaScript function and then access it outside of the function?

I have a Node.js application where I need to define a variable inside a function and access its value outside the function as well. Can someone provide guidance on how to achieve this in my code? var readline = require('readline'); var rl = read ...

"Every time an Ajax call is successful, the 'else' clause in

When it comes to using Ajax for user login in the system, I encountered an issue where the Ajax success function would always run the else statement even if the server returned a true Boolean value. This meant that even when the login credentials were vali ...

What is the best way to transform the data received from this function into a DataTable that can be used with the Google Charts API?

Is there a way to easily convert the data returned by this function into a format that Google Charts API can read? public function ajax_get_dates(){ $data = ([['date1' => '04/08/2016'], ['date2' => '05/08/2016& ...

What is the process for transforming the output of a query into JSON format in Oracle 12c?

In order to update a new column with JSON, it is necessary to convert the selected data into JSON format first. Below is the code that has been modified from the comment: SELECT a.col1 a.col2 b.col3 b.col4 from table AS JSON The desired output format i ...

Issue: SyntaxError - JSON Parsing Error: Unexpected character '<' found in JSON data

After completing the AJAX request, I understand why I am receiving this message. The controller action method is designed to redirect to another view if everything goes smoothly. In the case of an error, it should return JSON with an error message. As I g ...

Tips for eliminating any default white space visible between tags:

What is the best way to eliminate white space gaps between div tags and adjust pixel differences between them in HTML code? My current alignment is off and there are noticeable white spaces between div tags. I have tried using a reset link but it didn&apo ...

Toggle the visibility of a text area in a text editor based on the selected value in a

I currently utilize the NicEdit text-editor from www.nicedit.com on my Text Area, along with the following code to toggle the visibility of the text area after selecting a value from a drop-down. I need some assistance with the following: 1) I would like ...

The state change in NextJS button becomes visible after the second click

An avid learner exploring Next.js. I am eager to create a component that displays the window width and height along with a Tailwind CSS breakpoint when a button is clicked, as a first step towards continuous display. I chose to implement a button click ev ...

Confirm that the attributes of a JSON object align with an Enum

Having a Lambda function that receives a JSON object from the Frontend over HTTPS, I need to perform validation on this object The expected structure of the body should be as follows (Notifications): interface Notifications { type: NotificationType; f ...

Leveraging the same React component in multiple instances and streamlining requests - NextJS vs React

Currently, I'm working on a chat application using NextJS 14. Each time a message is sent or received, there is a small icon next to the chat message that represents the user who sent the message. To achieve this, I have a ChatMessageUI component tha ...

Merging various JSON files into a single JSON file using a bash script

I have a directory filled with subdirectories containing json files. My goal is to write a bash script that will merge all the individual json files into one large, valid json file. 1) Initially, I attempted to use jq to combine each set of json files wi ...

Implementing setTimeout with the copy button: A guide

How can I implement a setTimeout function in the copy button so that when a user clicks on it, the text will change to "copied" and then revert back to "copy" after 3-4 seconds? Please help me find a solution to this problem and also optimize the JavaScrip ...

Animating a dotted border path in SVG for a progress bar effect

I am attempting to create an animation for a dotted SVG circle that resembles a progress bar, where it fills itself over a duration of 3 seconds. However, I am facing difficulties in achieving this effect with the dotted border. The current code I have doe ...

Build a Docker container for a project that requires utilizing yarn link for dependencies

While working on my NextJS project, I made the decision to utilize yarn as my package manager and utilized yarn link for import aliases/absolute imports. This feature of yarn is quite handy and is recommended for managing aliases within a project. However, ...