Utilizing v-for in Vue with TypeScript to generate multiple checkboxes

My goal was to capture the values of checkboxes and store them in an array using v-model. However, I encountered an issue where the first time I toggle a checkbox, it doesn't register. Only after checking a second box and hitting submit does the second value get captured. Additionally, when attempting to select multiple checkboxes, only the last checked box gets logged after triggering the handleClick function. I also attempted console logging filter.filtProv and noticed that it only logs the most recently checked box.

//vue app
var filter = {
  filtProv: reactive([]) as String[]
}
var temp: any = []

let handleClick = () =>{
  temp.push(filter.filtProv)
  console.log(temp)
}


//template
<div id="checkboxes" v-for="provider in providerList" v-bind:key="provider" class="m-2">
   <input class="mx-1" type="checkbox" :value="provider" v-model="filter.filtProv"/>
   <label>{{provider}}</label>
</div>

Answer №1

To implement this functionality, include a checked parameter in each object within your providerList.

Here is an example structure:

{
  value: string,
  checked: boolean
}

Upon submitting the form, you can then filter out the objects with checked set to true from the array.

Check out this Demo :

new Vue({
  el: '#app',
  data: {
    providerList: [{
        value: 'first checkbox',
      checked: false
    }, {
        value: 'Second checkbox',
      checked: false
    }, {
        value: 'Third checkbox',
      checked: false
    }, {
        value: 'Fourth checkbox',
      checked: false
    }]
  },
  methods: {
    submitForm() {
      const result = this.providerList.filter((obj) => obj.checked).map((obj) => obj.value);
      console.log(result);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div id="checkboxes" v-for="(provider, index) in providerList" v-bind:key="index" class="m-2">
    <input class="mx-1" type="checkbox" :value="provider.value" v-model="provider.checked"/>
    <label>{{provider.value}}</label>
  </div><br>
  <button @click="submitForm()">Submit!</button>
</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

Managing the ajax response to showcase a button within datatables

Here is my current datatable structure: <table id="list" class="display" width="100%" > <thead> <tr> <th>Title</th> <th>Description</th> <th>delete</th> ...

Retrieving HTML content from Wikipedia's API using JavaScript

I am encountering an issue where every time I attempt to log data to my console, an error occurs. Could someone kindly point out what may be the problem with the code? My objective is to actually showcase the html content on a webpage. Below is the code ...

What is the reason this union-based type does not result in an error?

In my TypeScript project, I encountered a situation that could be simplified as follows: Let's take a look at the type Type: type Type = { a: number; } | { a: number; b: number; } | { a: number; b: number; c: number; }; I proceed to defi ...

Is there a way to track and monitor the ngRoute requests that are being made?

I am in the process of transferring a fairly large Angular 1.6 application from an old build system to Yarn/Webpack. Our routing is based on ngRoute with a complex promise chain. While sorting out the imports and dependencies, I keep encountering this err ...

How to redefine TypeScript module export definitions

I recently installed a plugin that comes with type definitions. declare module 'autobind-decorator' { const autobind: ClassDecorator & MethodDecorator; export default autobind; } However, I realized that the type definition was incorrec ...

Issue Arising During File Transfer in Nativescript

I am currently attempting to upload an image that I captured with Nativescript to a server using a web API that I created in C# (ASP.NET). The API works perfectly fine when tested on Postman, but I encounter an error "Error During Upload" while trying to u ...

How can I track the number of correct answers in a ReactJS quiz with an auto-submit feature and a timer that stops?

The auto-submit feature is not functioning correctly. Although the code works fine when I manually submit the quiz at the end, if the time runs out, the score will always be 0/3 which is incorrect. // React and Material-UI imports omitted for brevity // ...

Is there an array containing unique DateTime strings?

I am dealing with an Array<object> containing n objects of a specific type. { name: 'random', startDate: '2017-11-10 09:00', endDate: '2017-11-23 11:00' } My goal is to filter this array before rendering the resu ...

Eradicate lines that are empty

I have a list of user roles that I need to display in a dropdown menu: export enum UserRoleType { masterAdmin = 'ROLE_MASTER_ADMIN' merchantAdmin = 'ROLE_MERCHANT_ADMIN' resellerAdmin = 'ROLE_RESELLER_ADMIN' } export c ...

Unexpected Issue with Lightbox2 Functionality in Chrome Browser

Not too long ago, I reached out here for the first time with a similar issue: my image gallery on my art portfolio site was malfunctioning in Chrome, yet worked fine in Microsoft Internet Explorer and Edge. Thanks to some incredibly helpful and patient in ...

Angular6 table using *ngFor directive to display objects within an object

Dealing with Angular 6 tables and encountering a challenge with an item in the *ngFor loop. Here is my HTML view: <table class="table table-bordered text-center"> <tr> <th class="text-center">Cuenta</th> <th class="te ...

Utilize mouseover to rotate the camera in three.js

Is it possible to utilize Three.js to rotate a camera and view an object from all angles upon hovering with the mouse? ...

Guide to implementing the patchValues() method in conjunction with the <mat-form-field> within the (keyup.enter) event binding

I am currently working on a feature that populates the city based on a zip code input. I have successfully achieved this functionality using normal HTML tags with the (keyup) event binding. However, when trying to implement it using CSS, I had to use (keyu ...

Does AngularJS have a callback function for ng-bind-html-unsafe?

Is there a way to efficiently remove certain elements from the DOM after they have been added by this code snippet? <div ng-bind-html-unsafe="whatever"></div> I have created a function to remove these elements, but I am unsure how to trigger ...

Switch out all content located after the final character in the URL

In my code, I am using JavaScript to replace the current URL. Here is the snippet: window.location.replace(window.location.href.replace(/\/?$/, '#/view-0')); However, if the URL looks like this: domain.com/#/test or domain.com/#/, it will ...

Having Trouble with Axios PUT Request in React and Redux

I'm having trouble making a PUT request to the server. I understand that for a PUT request, you need an identifier (e.g id) for the resource and the payload to update with. This is where I'm running into difficulties. Within my form, I have thes ...

How can you ensure that it selects a random number to retrieve items from an array?

I am experiencing an issue with some code I wrote. Instead of displaying a random object from the array as intended, it is showing the random number used to try and display an object. <html> <body> <h1>HTML random objects< ...

Creating a function in Typescript to extend a generic builder type with new methods

Looking to address the warnings associated with buildChainableHTML. Check out this TS Playground Link Is there a way to both: a) Address the language server's concerns without resorting to workarounds (such as !,as, ?)? b) Dodge using type HTMLChain ...

Guide to TypeScript, RxJS, web development, and NodeJS: A comprehensive manual

Looking for recommendations on advanced web development books that focus on modern techniques. Digital resources are great, but there's something special about reading from a physical book. I don't need basic intros or overviews - consider me an ...

Having trouble accessing HikVision Web SDK functions in Angular 17

First and foremost, this concerns the HikVision cameras specifically. Because the SDK is compiled to plain JavaScript (with jQuery included), I had to import the JS files in angular.json and use declare in the component TS file (in this instance, camera.c ...