Obtaining a user id by clicking on a checkbox and then a button in Vue JS

My goal is to create user-specific checkboxes where clicking on a checkbox will allow the user ID to be retrieved using the getUserId method upon clicking the "Get user id" button.

To see the code in action, visit this CodeSandbox link

<template>
  <div>
    <div class="user" v-for="(user, i) in items" :key="i">
      <p>{{ user.name }}</p>
      <p>{{ user.age }}</p>
      <input type="checkbox" />
    </div>
    <button @click="getUserId()">Get user id</button>
  </div>
</template>

<script>
export default {
  methods: {
    getUserId() {},
  },
  data() {
    return {
      items: [
        {
          id: 1,
          name: "Alex",
          age: 23,
        },
        {
          id: 2,
          name: "Robert",
          age: 33,
        },
        {
          id: 3,
          name: "Jacob",
          age: 55,
        },
      ],
    };
  },
};
</script>

Answer №1

If you're looking to gather the selected user IDs, one way to achieve this is by linking your checkbox models to an array and assigning the value to user.id

new Vue({
  el: "#app",
  methods: {
    getUserId() {
      console.log("userIds", this.userIds)
    },
  },
  data() {
    return {
      items: [{"id":1,"name":"Alex","age":23},{"id":2,"name":"Robert","age":33},{"id":3,"name":"Jacob","age":55}],
      userIds: [] // initialize with an empty array
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <!-- Remember: using `user.id` as the key improves performance -->
  <div class="user" v-for="user in items" :key="user.id">
    <p>{{ user.name }}</p>
    <p>{{ user.age }}</p>
    <!-- Assign `user.id` as the checkbox value and link the model to the array -->
    <input type="checkbox" :value="user.id" v-model="userIds" />
  </div>
  <button @click="getUserId()">Get user id</button>
</div>

For further reference, visit https://v2.vuejs.org/v2/guide/forms.html#Checkbox

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

What is the best method for eliminating duplicate options from a datalist in HTML with the help of javascript or jquery?

I recently worked on enhancing a search box by using Flask, MySQL, and Ajax to enable search suggestions as users type in their queries. However, I encountered an issue where duplicate options were being generated and displayed due to similarities in the s ...

Is it a jQuery AJAX problem? Could it be related to cross-domain issues?

I'm currently working on implementing a tracking script that utilizes AJAX through JQuery. This is specifically for my personal use, so while aesthetics are not important, functionality is key. Essentially, I am incorporating scripts onto domains ow ...

Assign an array to a varied array size that is not predetermined

Recently, I've been delving into programming for my Arduino using a variant of c++. One particular program I've been working on involves cycling through every number on a 4-digit seven-segment display. However, I've encountered difficulties ...

The index.html file is failing to load/render when using app.js

I am currently in the process of creating a to-do list using an older tutorial. The app.js file seems to be functioning properly, however, when I try to run it locally, all I see is a blank page instead of my HTML content. Here is the code found in the ap ...

Angular 2 and Its Multidimensional Arrays

I'm having some trouble understanding Arrays in Typescript ( Angular 2 ). I am looking to create a specific array to send to my API. array = [ cadSocios => true, name => ['name1', 'name2'], part => ['part1', &ap ...

Using a pointer to provide data to OpenGL's glBufferData function

As a newcomer to OpenGL, I am exploring how to create a colored square. Following the guidelines from the tutorial provided by OpenGL Book, I used the example code available here. However, since the example draws a triangle, I made modifications to draw 4 ...

Stop or terminate all ongoing requests in AngularJS

When switching routes, I want to prevent any pending requests from the previous route in order to avoid issues where responses from the previous route interfere with data on the current route. This sometimes happens when responses from the previous route t ...

Differences between importing Component and Vue from "vue-property-decorator" versus importing Vue from "vue"

Can you explain the specific differences and scenarios where importing Vue from vue-property-decorator versus just vue would be applicable? I have learned that when defining a custom component with a @Component decorator, it is necessary to import Vue fr ...

Deactivate the jQuery function based on the size of the window

I have a jQuery script that should be activated based on the size of the window. The current code works fine when the page loads, but it doesn't respond to window resizing as expected. The jQuery functions don't enable or disable according to th ...

Sophisticated method for implementing dynamic components with props in Vue

In a specific scenario, I am using an API to output all the content for my Page, including its structure. To provide context, imagine a CMS with a page builder feature where authors can place components via drag and drop to create pages, which are then del ...

Is there a way to send the HoDjango views.py context data variable to the ng-repeat filter?

I am attempting to implement a filter in Angular's ng-repeat where the value of selectedUserId is derived from a context_dict variable. The curly braces I am using for Angular are {--} This is my view.py file - extracting the user_id from the URL de ...

Tips for setting a uniform width for all bars in apexcharts bar column width

When working with dynamic data, the length of the data should also be variable. For instance, if the data has a length of 24, the column width should be 35px; similarly, even if the data has a length of 2, the column width should still be 35px. Apexchart ...

"Learn how to showcase a picture in full-screen mode when the webpage is opened

I recently came across a script on Stack Overflow that allows me to select an image at random from an array. The script can be found here: Script to display an image selected at random from an array on page load However, I want to take this concept furthe ...

Transferring form array data through AJAX

My PHP script requires two values: operation => string and data => array. The form below contains dynamically generated inputs: <form method="post" action="/operations.php"> Title: <input type="text" value="valuehere" name="data[tit ...

By employing timeUpdate in conjunction with currentTime

I am looking to utilize the timeUpdate and currentTime functionalities to display or hide a div at a specific time during video playback. I have been able to make it work, but it seems to be showing and hiding every second I specify. Below is the code I ...

Is It Possible to Create Flash Content Without Using a SWF File?

Is there a way to embed Flash directly in HTML, rather than linking to an external SWF file? I am looking to send an HTML form via email for the recipient to fill out by opening it in a browser. The final step would involve copying the result to their clip ...

Which is the Better Choice for an MMO WebSocket Server: Node.js or C++?

Contemplating creating a live game using WebSockets for the web has been on my mind. With my knowledge of Node.js, it's tempting to develop it there. However, C++ appears to be the favored server language due to its speed. Would it be best to try bui ...

The value of the variable in the controller is not being successfully assigned the data that is resolved

//in a PService module this.fetchTypes = function(){ var types = PTypesFactory.retrieve({}); return types.$promise.then(function(result) { console.log(result.groups); return result.groups; }); } ...

Using Laravel and Ajax to fetch and display checkbox data from a database array

I have a challenge with retrieving data from the database and displaying it as checked checkboxes. The data in the database is stored as an array inserted using JSON, and it's dynamic based on user input. Here's a snippet of my tasks table: id ...

Unsure if values can be imported from one component to another in Vue.js using props

Currently experimenting with Vue and ran into a minor challenge - wondering if there's a solution to this. I am looking to add a new value to my items array using my Button component so that I can display it using v-for. While consolidating everything ...