jquery system for rating stars

I am currently working on implementing a star rating system that displays the rating when a star is clicked.

(Just to clarify, I have multiple similar divs which is why unique IDs are not assigned to each star (span))

HTML:

    <div id="rating1" class="rating">
        <span>★</span><span>★</span><span>★</span><span>★</span><span>★</span>
    </div>

jQuery:

    $(document).ready(function(){

$("#rating1 span:nth-child(1)").click(function()
{
    if (x == 5)
    {
        alert("You rated 1 star");
    }
    if (x == 4)
    {
        alert("You rated 2 stars");
    }
    if (x == 3)
    {
        alert("You rated 3 stars");
    }
    if (x == 2)
    {
        alert("You rated 4 stars");
    }
    if (x == 1)
    {
        alert("You rated 5 stars");
    }
  });
});

If you're curious about the reversed numbers in $("#rating1 span:nth-child(1)"), it's due to the CSS styling where preceding stars light up upon hovering over a star. Since only succeeding stars can be highlighted, I had to reverse them using "direction: rtl;".

The issue I'm facing is wanting to replace the static number 1 with a variable X that changes based on the clicked star - i.e., clicking the first star assigns x=5, and so on. As a jQuery novice, I would greatly appreciate a comprehensible answer. The "alert" function is just for testing purposes; ideally, the rating should display below.

If any part is unclear, feel free to inquire so I can update my query. Apologies if it's a bit convoluted; I'm still a beginner in both programming and Stack Overflow.

Answer №1

Modify

$("#rating1 span:nth-child(1)")

to

$("#rating1 span")

and implement the use of .index to retrieve the index of the clicked element:

$("#rating1 span").click(function() {
  var x = $(this).index() + 1;
  alert(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rating1">
  <span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
</div>

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

Is it possible for <h2> to utilize React's onLoad event?

I need assistance with creating a dynamic calendar that displays the current month upon page load. I am using HTML format within a React JS file. <h2 onLoad={curMonth}></h2> To achieve this, I have imported the curMonth function from another f ...

CSS causing unexpected behavior in image slider

I am facing an issue with incorporating a code for an image slideshow into my website. The current CSS is causing the slideshow to malfunction. Without the slideshow code in the CSS, the image appears correctly on the screen and changes its source every 2 ...

Having difficulty extracting specific data from the table

I am currently utilizing selenium and Python to extract data from a website. However, I am encountering difficulties while trying to scrape a specific table using Beautiful Soup. Here is the code snippet: from selenium import webdriver from selenium.webdr ...

What steps can I take to fix the issues on Safari that are being caused by three js on my website?

For my friend's birthday, I decided to surprise him by creating a web page for his online radio station. Being new to JavaScript, it was a great learning opportunity for me. After much experimenting, I finally got the page to work smoothly on desktop ...

Showcasing top performers via JavaScript tabs

I have two tabs on my webpage: "Overall Leaderboard" and "Weekly Leaderboard". Each tab displays a leaderboard with different scores. When I click on the "Overall Leaderboard" tab, it shows a leaderboard with specific scores. Now, my question is how can ...

Is it not possible to use a hyperlink and the general sibling combinator simultaneously?

Hi everyone, I'm completely new to CSS so please bear with me as I try to explain my issue. I'm attempting to create an image hyperlink using the .link class. I want the images for both .link and .picture to "change" when I hover over the hyperl ...

Swap the hyperlink and heading upon clicking

I need to implement a function where a sort bar changes URLs and titles on click. For example, when a link like this is clicked: <a href="http://localhost/11/affiliate/?post_type=affiliate&orderby=title&order=asc ">Title ASC</a> It sh ...

Can you navigate between slides with JQuery?

Looking to create a website similar to . The only obstacle I am encountering is understanding the code. I prefer using JQuery over MooTools. Is there anyone who can kindly assist me by providing a demo? I want to implement the functionality of switching b ...

Adding choices to enhance dual List styling

var demo2 = $('#tree_listbox').bootstrapDualListbox({ nonSelectedListLabel: 'Non-selectedsss', selectedListLabel: 'Selected', moveOnSelect: false, }); var data = [ { "id": 194, "name": "Endüstri Mühendisliğ ...

AngularJS utilizes JSON objects to store and manipulate data within

My task requires accessing information from an array that is nested inside another array in Json format. Here's a more detailed example: [ { "id": 1, "name": "PowerRanger", "description": "BLUE", "connections": [ {"id": 123,"meg ...

Python script to extract data from a dynamic JavaScript webpage

I've been involved in a research project where we are aiming to gather a list of reference articles from the Brazil Hemeroteca (The specific page reference we are seeking: , needs to be located by extracting data from two hidden elements on this page: ...

Is it HTML True or False in the editor?

For the HTML template I'm working on, I want to implement a feature where users can toggle tags on and off easily. My idea is to make it as simple as setting a value to "true" or "false." Is there a way to achieve this within a single HTML file? ...

Exploring the world of CSS: accessing style attributes using JavaScript

So I created a basic HTML file with a div and linked it to a CSS file for styling: HTML : <html> <head> <title>Simple Movement</title> <meta charset="UTF-8"> <link rel="stylesheet" type=&qu ...

try out testing with the mock declaration in Jasmine test

My service involves loading a variable from a JavaScript file fetched from a CDN (without a typedef). To handle this, I have created a declaration for the variable: declare const externalValue: string; @Injectable() export class Service { ... Everythi ...

Clicking on the icon image that features a Background Video will trigger the video to play in a popup window originating from the same location

A background video is currently playing on the site. When the play icon is clicked, the video should start playing in a popup. The video should start playing continuously from the exact moment and position where it is clicked. Check out the example here. ...

What is the method for retrieving a specific item within an array object using its index number?

How can I access the object '2016-11-12' inside the $scope.list and display the Order and Balance values? List: $scope.list = { ItemCode:'item1', '2016-11-12':[{Order:'1',Balanace:'2'}], '2016- ...

Guide on sending a request to an API and displaying the retrieved information within the same Express application

I recently developed a basic express app with API and JWT authentication. I am now attempting to enhance the app by incorporating page rendering through my existing /api/.. routes. However, I am facing challenges in this process. app.use('/', en ...

Tips for adding a progress bar to your sidebar

I have a query regarding how to expand the width of a div within an li element. Essentially, as a user scrolls, the sidebar on the right-hand side will cause the span element (highlighted with a red background color) inside the li to transition from 0 to ...

What are the recommended guidelines for organizing files in an NPM package for front-end development?

I am creating an NPM package for the front-end and I'm trying to figure out the optimal file structure. My package consists of a code.js file as well as a code.min.js file. Should these files be located in the root directory, a dist folder, or a src f ...

I am having trouble showing the background image in the div

I created a 960 layout using 3 divs to easily organize child divs with images and text. However, I'm having trouble getting the background image of the first div to display. Can you help me figure out what I'm doing wrong? This is the concept f ...