Implementing VueJS - Automatically setting a radio button as checked based on matching ID values

In my array, I store objects (products) where each product has its own rating that is retrieved from the database. The average rounded rating of each product is displayed on the product itself.

{{ Math.round(Object.values(product.rating)[0]) }}

I want to show this average value using stars (radio buttons) for users to rate a product. When someone rates a product by clicking on the stars, the corresponding number of stars based on the current rating should be checked. When dealing with multiple products in a list, each with different ratings, how can this be achieved?

Each radio button in the UI has an ID and value attribute. How can these attributes be matched with the current rating of the product?

Attempts were made using this but it didn't work as expected:

<div class="rating">
  <input
    type="radio"
    value="5"
    id="5"
    :checked="
    this.value ==
    Math.round(Object.values(product.rating)[0])
    "
    @change="rateproduct"
    /><label for="5">☆</label>
  <input
    type="radio"
    value="4"
    id="4"
    @change="rateproduct"
    :checked="
    this.value ==
    Math.round(Object.values(product.rating)[0])
    "
    /><label for="4">☆</label>
  <input
    type="radio"
    value="3"
    id="3"
    @change="rateproduct"
    :checked="
    this.value ==
    Math.round(Object.values(product.rating)[0])
    "
    /><label for="3">☆</label>
  <input
    type="radio"
    value="2"
    id="2"
    @change="rateproduct"
    :checked="
    this.value ==
    Math.round(Object.values(product.rating)[0])
    "
    /><label for="2">☆</label>
  <input
    type="radio"
    value="1"
    id="1"
    @change="rateproduct"
    :checked="
    this.value ==
    Math.round(Object.values(product.rating)[0])
    "
    /><label for="1">☆</label>
</div>   

An alternative approach that was attempted also did not yield the desired outcome:

<input
  type="radio"
  value="5"
  id="5"
  :checked="
  Math.round(Object.values(post.rating)[0])
  ? 'checked'
  : ''
  "
  @change="ratePost"
  /><label for="5">☆</label>
</input>

The goal is to enable users to rate each post individually by checking the appropriate number of stars based on the post's rating. However, only the last post rating gets selected.

<template>
    <div class="postsList">
        <div class="post" v-for="post in posts" :key="post.id">
            <div class="title">Title: {{post.title}}</div>
            <div class="currentrating">Rating: {{post.rating}}</div>
            <div class="vote">
                <div class="rating">
                    <div class="star" v-for="index in stars" :key="index">
                        <input
                            type="radio"
                            name="stars"
                            :value="index"
                            v-model="post.rating"
                            @change="ratePost"
                        /><label>☆</label>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
  import {ref} from 'vue'
    const stars = 5;
    const posts = ref([
        { id:1, title: "post1", rating: 2 },
        { id:2, title: "post2", rating: 3 },
        { id:3, title: "post3", rating: 2 },
        { id:4, title: "post4", rating: 5 },
        { id:5, title: "post5", rating: 2 },
        { id:6, title: "post6", rating: 1 },
        { id:7, title: "post7", rating: 2 },
        { id:8, title: "post8", rating: 3 },
        { id:9, title: "post9", rating: 4 },
        { id:10, title: "post10", rating: 1 },
    ]);
</script>

<style scoped>
  .post{
    padding:10px;
  }
  .rating{
    display:flex;
    margin-bottom: 10px;
  }
  .title{
    margin-bottom:10px;
  }
  .currentrating{
    margin-bottom:10px
  }
</style>

Answer №1

Here is a potential solution:

https://i.sstatic.net/EdyiR.gif

https://sfc.vuejs.org/#eNqtVlFv0zAQ/iunvDQTbUIHCBTawh4mNGnjgcGERBHyEjf15jiR7Xatqv53znbSum0yCbROmpK7777L3X2+ZBNcVFW0XNAgCUaaFhUnmk6mAvA3mjHKM0V1fW9tnOZUZJOLJZUkp3CriYRvRDORj+La56EztoSUE6XG00CSjJVqGnj+dswXWS6qaQDLwayUaGQioytgAm4ufv65u7j+cYnO5JGuG98Jp+VlolpoOHWYn15XtEmHZO0gQQoDUlgiPnYHKFkSvjCw+kk6YMtBUWaU13R3JqYT+znlLH2MKkmXVGgMwb8TYNxWMif3lE82G2yWadl2C3htEn6nKx1a4xlacVIWeDSIGCfhD+/4/vDW/BoVOAEkJhvg8DBPVrtspZiynXYUH0nsOcldCQxk2YJwuEKl1klVl+wa9YSKs...

<template>    <fieldset>        <legend>Average Star Rating</legend>        <div class="radios">            <div class="radioGroup" v-for="index in MAX_VALUE" :key="index">                <input                     type="radio"                     name="stars"                     :value="index"                     v-model="starValue"                     @click.prevent=""                />                <label>{{ index }} {{ starText(index) }}</label>            </div>        </div>        <div>            Average Rating: {{  roundedAverageValue }}        </div>    </fieldset>    ...

Note that the code you previously shared has an issue with the radio inputs inside the loop where they share the same name attribute. To fix this, each group of stars should have a unique name property for the radio input.

The updated version now includes a rating panel component displaying 5-star ratings using checkboxes and showcases individual item ratings along with an average calculation handling multiple components efficiently.

RatingPanel.vue

<template>
    <div class="star-panel">
        ...
    </div>
</template>
...

MultipleRatings.vue

<template>
    <div class="post-list" v-for="post in posts" :key="post.id">
        <SingleRatingPanel :title="post.title" v-model="post.rating" />
    </div>
</template>

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

Verifying user credentials using Ajax

I am attempting to implement Ajax for the validation of a username and password stored in a php file on a server. The credentials are pre-defined in the document itself. Within my HTML page, there are fields for entering the username and password. When th ...

The annoying pop-up refuses to vanish even after clicking on the "Stop Capture" button during screen recording

I'm dealing with an issue regarding popups. Whenever I choose "get audio from desktop" and click on "Start Recording", another browser popup appears, prompting me to make another decision (this involves selecting the screen and sharing audio). I' ...

What is causing the CSS loader to continue showing up even after all the items have finished loading?

I have been developing an innovative newspaper/blogging platform using CodeIgniter 3.1.8 and Twitter Bootstrap 4. Currently, my focus is on implementing the AJAX functionality to load more posts dynamically. The default setup paginates the posts, display ...

What is the best way to display a fresh jade view when a socket event occurs?

In my project, I am utilizing two key JavaScript files - one on the server side named server.js and another on the client side known as enterchat.js. These files are responsible for communicating via socket.io and all socket events are functioning as inten ...

Transferring data from a stream in NodeJS to FrontEnd using ReactJS

How are you doing? I'm trying to figure out how to send a large data request from PostgreSQL to the FrontEnd in JSON format. Can anyone help with an example of how this can be achieved? Thank you. Here is my code: const express = require('expr ...

Why won't the button's color change when I try clicking on it?

I am currently learning vue and facing some challenges. The code I have is supposed to change the button color when clicked, but it's not working as expected. Any advice on how to fix this issue would be greatly appreciated. Thank you! let app = ...

Is there a way to retrieve the response body in Express framework?

In my NodeJS API using Express, I am attempting to save the response body of a request. To achieve this, I have created two middleware functions. app.use((req, res,next) => { res.status(404).json({ errors: [{ field: "url", ...

I am facing an issue where I am unable to display the data received from axios response.data in

I am completely new to this, and my question may seem simple, but I haven't been able to find a solution yet. It's really important for me to figure this out. I've been trying to retrieve data from a GitHub repository using a REST API, but I ...

Updating individual items in the Redux state while displaying the previous version

I'm facing an issue with updating the reducer for my items (icdCode) in my array (icdCodes) within a React component. The update works only after reloading the entire component, which is not ideal. Initially, I had to deal with a duplicate key problem ...

Exploring Textures with Three.js

I'm attempting to add a texture to the birds example in the three.js library. // creating a loader instance var loader = new THREE.TextureLoader(); // loading the texture resource loader.load('imgs/birdtexture.jpg',function (text ...

Enable only the current week days on the multiple date picker feature

Can anyone recommend a date picker that only shows the current week and allows for multiple date selections by the user? I found this jsfiddle which limits the display to the current week, but it doesn't support selecting multiple dates. I attempted ...

Converting JSON data into an array containing individual objects, and inserting a new item into each object

I've been working on retrieving data from a JSON file and successfully creating an array of objects. However, I am trying to add an item to each object in the array simultaneously. Check out my current code: var linklist = []; $.getJSON('links. ...

Enhancing the asp.net MVC link element with an ID property

I am currently working on a web application that contains the following link: <a href="@planUrl">@ResourceManager.GetResource("MemberLinkText")</a>. I need to add an ID to this link in order to incorporate a $(document).onClick() handler. Howev ...

Can someone explain the distinction between 'return item' and 'return true' when it comes to JavaScript array methods?

Forgive me for any errors in my query, as I am not very experienced in asking questions. I have encountered the following two scenarios :- const comment = comments.find(function (comment) { if (comment.id === 823423) { return t ...

Unable to load CSS background image

As I develop a website for a fictional company to enhance my skills in HTML, CSS, and JavaScript, I am encountering an issue with loading my background image. If someone could review my code to identify the problem, I would greatly appreciate it. Check ou ...

Typescript is throwing an error with code TS2571, indicating that the object is of type 'unknown'

Hey there, I'm reaching out for assistance in resolving a specific error that has cropped up. try{ } catch { let errMsg; if (error.code === 11000) { errMsg = Object.keys(error.keyValue)[0] + "Already exists"; } return res.status ...

Inject JSON data from jQuery into Thymeleaf template

I've successfully retrieved data using the Google Books API for ISBN, but I'm struggling to integrate that data into a form. Below is my jQuery code: $(document).ready(function(){ $('#submitCode').click(function(){ var x; ...

Dynamic links within Vue router can cause issues with page reloading and some components not loading correctly

Within my project's routes file, I have added a new path with nested children: path: '/warehouse/:id', name: 'ShowWarehouse', component: ShowWarehouse, children: [{ path: 'edit', name: 'EditWarehouse ...

Manipulating Keys in JavaScript Arrays of Objects dynamically

I am facing a challenge where I need to switch keys with values within an array of objects var myArray = [ {'a' : {'x': ['Bob', 'Rob', 'Mike'], 'y': [4,5,6], 'name': &apos ...

Develop a customized modal pop-up for every object using React

In my React app, I have a list of cards with buttons on each one. When the button is clicked, it should open a modal popup displaying some information. However, I am facing an issue where I can't create a unique modal for each card because the data t ...