Using Vue.js to bind labels and radio buttons in a form

My goal is to generate a dynamic list of form polls based on the data. However, using :for or v-bind:for does not result in any HTML markup appearing in the browser, causing the labels to not select the corresponding input when clicked. I have prepared a JSFiddle for reference (Note: SCSS may not work in JS Fiddle). This project is built with Nuxt.

Here is the code snippet: https://jsfiddle.net/mc4rdle/o19bgjpe/2/

Markup:

<div class="option" v-for="answer in poll.answers" :key="answer.answer.id">
  <input type="radio" :id="answer.id" :value="answer.answer">
  <label class="option" :for="answer.id">
     <div class="indicator"></div>
     <div class="label">{{ answer.answer }}</div>
   </label>
</div>

Data: polls: [

{
                    id: 1,
                    question: 'How do you feel about your current salary?',
                    answers: [
                        {
                            id: 1,
                            answer: 'Satisfied'
                        },
                        {
                            id: 2,
                            answer: 'Content'
                        },
                        {
                            id: 3,
                            answer: 'Unhappy'
                        }
                    ]
                },
                {
                    id: 2,
                    question: 'What group activity should we do??',
                    answers: [
                        {
                            id: 1,
                            answer: 'Yoga'
                        },
                        {
                            id: 2,
                            answer: 'Table Tennis'
                        },
                        {
                            id: 3,
                            answer: 'Pints'
                        }
                    ]
                }
            ]

Thank you in advance :)

Answer №1

Your input identifier is currently duplicated as it is solely based on the answer's id. To make it unique, you can combine both the poll.id and answer.id, like this: poll.id + '-' + answer.id


<div class="option" v-for="answer in poll.answers" :key="answer.answer.id">
      <input type="radio" :id="poll.id + '-' + answer.id" :value="answer.answer" :name="poll.id">
      <label class="option" :for="poll.id + '-' + answer.id">
        <div class="indicator"></div>
        <div class="label">{{ answer.answer }}</div>
      </label>
    </div>

Check out the demo on jsfiddle

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

Query key array failing to update when key is modified

Encountering an issue with the query key array not updating when the selected warehouse ID is changed. This causes useQuery to use outdated data instead of fetching new data for the updated warehouse ID. Struggling to figure out how to update the query k ...

Accessing data returned from JSON in JQuery beyond the code block required

Is there a way to access returned JSON data outside of the JQuery getJSON method? For example: var price = ""; $.getJSON("../JSONDeliveryPrice", null, function (data) { price = eval(data.price); }); console.log(price); Unfortunately, this code does not ...

Having difficulty creating a snapshot test for a component that utilizes a moment method during the rendering process

I am currently testing a component that involves intricate logic and functionality. Here is the snippet of the code I'm working on: import React, { Component } from 'react'; import { connect } from 'react-redux' import moment from ...

The server failed to trigger the SignalR method

There are two methods on the server that can be invoked, both are very similar. However, only one of them (SubscribeToWatchlist) is being executed on the server side when called. The UnsubscribeFromWatchlist method is not working as expected. ASP.NET Cor ...

Tips for accessing information from an Angular Resource promise

I am currently facing an issue when trying to read data from an angular promise that was returned. Before, I had the following code: var data = category.get({id:userid}); Later, I realized that the data being returned was an unresolved promise. So, I ma ...

What is the best way to retrieve a date (value) from a DatePicker and then set it as a property in an object

I am currently utilizing the react-datepicker library, and I have a question about how to retrieve a value from the DatePicker component and assign it to the date property within the Pick object. Extracting data from regular input fields was straightforw ...

Node.js Project Using a Specific URL and Parameter

Two things are on my mind: 1. I'm trying to set up my project's URL as 127.0.0.1:8080/param=id, but I've been unsuccessful so far despite attempting the following: app.get('/param=id', function(req, res) { console.log(req.param ...

ReactJS - troubleshooting webcam video stream issue

I can't figure out why this code is not working properly. I am able to access the camera stream and see the light on my camera indicating that it's working, but the stream doesn't seem to be attaching correctly. class VideoOutput extends ...

Currently, my goal is to create a functional copy button through the use of JavaScript

I've been attempting to create a basic copy button using JavaScript, but I keep encountering an error. TypeError: null is not an object (evaluating 'myInp.select') Whenever I click the copy button, My code looks like this: <!DOCTYPE htm ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

Is it necessary for Vue single file components (.vue files) to use `export default` or is it possible to use named exports instead?

export default may no longer be the recommended way to export modules, as discussed in these resources: After changing my Vue components from this: <script lang="ts"> 'use strict'; import {store} from '../../data/store' ...

What are the benefits of using .factory instead of declaring a variable in AngularJS?

As I delve into learning Javascript and Angular JS, I'm exploring alternative approaches to using .factory. Instead of declaring what it returns as a variable and referencing it, I'm curious if there's a way around using factory. Why is fac ...

The body parser is causing issues with decoding base64 strings

When my mobile app sends a base64 string to my Express server via a POST request, the image is transmitted to a Google client endpoint. However, an error is returned saying: Provided image is not valid code: 400, 0|index | errors: [ 0|index | { 0 ...

Creating vibrant squares using HTML and CSS

My objective is to incorporate 3 input options for selecting the color, size, and amount of cubes. The image below showcases my peer's final project, but unfortunately, he refused to share the code with me. We were given a basic template to begin with ...

Using Jquery Mobile to make an AJAX POST request with XML

Is it possible to use this code for XML parsing? I have successfully parsed using JSON, but there is no response from the web service. This is the status of the webservice: http/1.1 405 method not allowed 113ms $j.ajax({ type: "GET", async: false, ...

Executing a function in ExpressJS at regular intervals of 24 hours

Can someone share the most effective method to schedule an automated task every 24 hours in ExpressJS? I have thoroughly researched possible solutions but haven't found any option other than using an infinite loop. Is there only one way to achieve th ...

Node.JS 3DES encryption encountering an issue with IV length validation

I'm new to working with Node.js and I've encountered an issue with the encryption object: var des3_key = new Buffer("redacted", "base64"); // obtained from another source var des3_iv = new Buffer("alsoredacted", "base64"); // obtained from anoth ...

Guidelines for creating an auto-scrolling React Native FlatList similar to a Marquee

I currently have a FlatList component set up in my project. <FlatList horizontal data={data} key={(item, index) => index.toString()} ListHeaderComponent={listHeader} renderItem={ // renderin ...

Create an Interactive Data Visualization with JSON using CanvasJS Charts

Having some trouble creating a chart using CanvasJS. After fetching data from the API and checking the JSON array, I encounter two errors when attempting to generate dataPoints for the graph: "data invalid" on the data field and "NaN" on the value field. ...

The error occurred while trying to cast the value of "{{Campground.name}}" to an ObjectID. This value, which is of type string, could not be converted to an ObjectID at the path "_id" for

const express = require("express"); const session = require("express-session"); const cookieParser = require('cookie-parser') const mongoose = require("mongoose"); const { Campground, User, Review } = require(" ...