Tips for iterating through a list of checked values using v-for

Currently working on a feature to create a checkbox that allows only one selection.

<div id="app">
 <div v-for="(question, index) in questions">
   <input type="checkbox" value="question.value" v-model="additional_grouped"  @change="uniqueCheck"> {{question.title}}
  </div>
  {{ result }}
</div>

Snippet of my JavaScript:

new Vue({
  el: '#app',
  data() {
    return {
      additional: [],
      additional_grouped: [],
       questions: [
         {
           title: 'A',
           value: 0
         },
         {
           title: 'B',
           value: 1
         },
         {
           title: 'C',
           value: 2
         }
       ]
    }
  },
  computed: {
    result: function(){
      return this.additional.concat(this.additional_grouped);
    }
  },
  methods: {
    uniqueCheck(e){
      console.log(e)
      this.additional_grouped = [];
      if (e.target.checked) {
          this.additional_grouped.push(e.target.value);
      }
    }
  }
});

Here is the original outcome.

https://i.sstatic.net/0BGtX.png

Aiming to achieve a result similar to this.

https://i.sstatic.net/iRMJK.png

While there are other methods available, I prefer utilizing the v-for method due to the volume of data. How can I ensure only one value is checked in v-for?

Check out my code on CodePen: enter link description here

Answer №1

You need to include the value binding (:value) in your code. Here is the corrected version of your example:

new Vue({
  el: '#app',
  data() {
    return {
      additional: [],
      additional_grouped: [],
       questions: [
         {
           title: 'A',
           value: 0
         },
         {
           title: 'B',
           value: 1
         },
         {
           title: 'C',
           value: 2
         }
       ]
    }
  },
  computed: {
    result: function(){
      return this.additional.concat(this.additional_grouped);
    }
  },
  methods: {
    uniqueCheck(e){
      this.additional_grouped = [];
      if (e.target.checked) {
          this.additional_grouped.push(e.target.value);
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
 <div v-for="(question, index) in questions">
   <input type="checkbox" :value="question.value" v-model="additional_grouped"  @change="uniqueCheck"> {{question.title}}
  </div>
  {{ result }}
</div>

Check out the official documentation

Answer №2

utilizes the syntax

:value="question.value"
in place of value="question.value"

new Vue({
  el: '#app',
  data() {
    return {
      additional: [],
      additional_grouped: [],
       questions: [
         {
           title: 'A',
           value: 0
         },
         {
           title: 'B',
           value: 1
         },
         {
           title: 'C',
           value: 2
         }
       ]
    }
  },
  computed: {
    result: function(){
      return this.additional.concat(this.additional_grouped);
    }
  },
  methods: {
    uniqueCheck(e){
      this.additional_grouped = [];
      if (e.target.checked) {
          this.additional_grouped.push(e.target.value);
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
 <div v-for="(question, index) in questions">
   <input type="checkbox" :value="question.value" v-model="additional_grouped"  @change="uniqueCheck"> {{question.title}}
  </div>
  {{ result }}
</div>

Answer №3

To obtain an array containing the values of the checkboxes that are checked, you can simply follow these steps:

<div id="app">
 <div v-for="(question, index) in questions" :key="index">
   <input type="checkbox" v-model="question.checked"> {{question.title}}
  </div>
  {{ result }}
</div>

Additionally, include the following code:

new Vue({
  el: '#app',
  data() {
    return {
       questions: [
         {
           title: 'A',
           value: 0
         },
         {
           title: 'B',
           value: 1
         },
         {
           title: 'C',
           value: 2
         }
       ]
    }
  },
  computed: {
    result: function(){
      return this.questions.filter(q => q.checked).map(q => q.value)
    }
  }
});

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

JavaScript code may fail to load on initial page load

My JavaScript function utilizes ajax and is triggered when a button is clicked. Oddly, the function works perfectly if you visit the page for a second time, but fails to work on the first visit. I've attempted to include window.onload, document.onlo ...

CSS Testimonial Slider - Customer Feedback Display

I'm having some issues with the code below: <div id="box"> <div class="wrapper"> <div class="testimonial-container" id="testimonial-container"> <div id="testimon ...

Challenge with modal dialog scrolling on iPad and iPhone

Our website contains various pages that open JQuery 'Modal Dialog' boxes. These modal dialog boxes function well in all web browsers. However, there is an issue when viewing the website on an iPad or iPhone, which seems to be a common problem. ...

Sinon threw an assertion error out of the blue

Just diving into using Sinon and facing a small hiccup. Let's say we have a module (named myModule.js) defined as follows: //myModule.js var _f2 = function() { console.log('_f2 enter'); return {prop1:'var1'}; }; var f1 = ...

Encountering an issue with NPM while attempting to install Parcel

After trying multiple solutions from various online sources, I am still unable to resolve the issue. Any advice or recommendations would be highly appreciated! npm ERR! code 1 npm ERR! path C:\Users\Tarun\Desktop\NamasteReact\node_ ...

What is the proper way to utilize --legacy-peer-deps or enforce in a vite build?

I encountered an issue with a package called react-typed in my project. To install it, I had to use --legacy-peer-deps. When deploying, I need to use vite build. However, when I run the command, I receive the following errors: 8:59:31 AM: npm ERR! node_mo ...

Client component in Next.js is automatically updated upon successful login

I am currently working on a Next.js + DRF website that requires authentication. I have set up my navbar to display either a "log in" or "log out" button based on a boolean prop passed from the server side to the client-side: export default async function R ...

Issue with vue-apollo package causing GraphQL query not to display on the frontend

Currently, I am expanding my knowledge of GraphQL and working on a project where I aim to display queries in the front end. To achieve this, I have incorporated the package GitHub - Akryum/vue-apollo: ...

Saving search results using AJAX in Vue and Laravel's database

I am working towards creating a feature with two input fields where users can type in the three-letter code of an airport. Through AJAX, a query will run to verify if the airport exists in the database. If it does, the name of the airport will be displayed ...

Creating intricate mazes using canvas drawing techniques

I recently developed a maze generator as a personal project utilizing a graph. While the generation logic works perfectly, I am facing challenges when it comes to rendering the maze. In my approach, each cell is represented by an array of 4 edges where the ...

Transmitting a single event to child components

Having a bit of trouble implementing something that I thought would be straightforward. In my Vue application, I am looping through a list where each item is a child component. Each item has an expand/collapse button, which is functioning correctly. Howev ...

Tips for Deactivating a Button Following a Single Click

I am currently developing a react-native app and I'm in need of assistance with my code stack. My requirement is to disable a button after it has been clicked once. Can anyone provide guidance on this issue? The challenge I am facing is that I cannot ...

Extending the href value using jQuery at the end

Can someone help me with this link: <a id="Link" href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2745425453424b4b524940674e0a4355464e4909494253">[email protected]</a>?subject=I-Drain Bestellung& ...

``JsViews and AngularJS: A Comparison"

I'm exploring the possibility of creating a single page application and came across jsViews/jsRender which seems very promising as it approaches Beta. As someone new to SPA development, I'm interested in understanding how jsViews stacks up agains ...

Leveraging TipTap.dev for building a joint editing platform -

I have integrated the collaboration feature from tiptap.dev into my NextJS application. Initially, I used their CLI command for the Hocuspocus server which worked well on port 1234 locally and synchronized text editing across browsers seamlessly. However, ...

Is it possible to integrate Vue.js with Laravel and bootstrap in a web development project?

In order to build a basic website equipped with a forum feature, my plan involves integrating Vue JS with Laravel and Bootstrap. I am confident in the necessity of Vue JS for this project, but I am open to alternative options for Laravel and Bootstrap. I ...

Using PHP/JavaScript to activate a button once the timer reaches 00:00

I came across a JavaScript fiddle code that is working perfectly. Here it is: HTML <div id="worked">00:05</div> JS $(document).ready(function (e) { var $worked = $("#worked"); function update() { var myTime = $worked.h ...

Troubling inconsistency in jQuery's .css function performance

I'm facing a problem with the jquery .css function. I am using it to retrieve the actual height of elements that have their height set to auto. The code I am currently using is as follows: $(this).css({ height: $(this).css("height"), width: $(this).c ...

Display or conceal a <div> segment based on the drop down selection made

A dropdown menu controls the visibility of certain div elements based on the selection made. While this functionality is working for one dropdown, it's not working for another even though the code is very similar. I've tried various solutions but ...

Utilizing React Javascript leaftlet library to implement functionality to zoom in on map using state

As a beginner in programming and leaflet, I've encountered a roadblock in my code. Check out my code snippet: import "./App.css"; import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet"; import { useEffect, useState ...