Accessing checkbox values within a vue.js component

Recently, I delved into the world of vue.js and have been trying to familiarize myself with it.

I've spent quite a bit of time tinkering around to make this simple example function: extracting the values of selected checkboxes in components using vue.js .

You can view my example at http://jsbin.com/gukoqo/edit?html,js,output

How can I ensure that the parent instance's selected property contains the selected checkbox values? For example, if filter_a and filter_c are selected, then selected should be an array: ['filter_a', 'filter_c']

I assumed that vue.js would provide a straightforward solution for this, but I am still unclear about how to achieve it. Any insights? :)

I'm working with the latest version of vue.js (2.3.3 currently).

Answer №1

Here is a potential solution.

Vue.component('facet-filter', {
  props: ['filter', 'checked'],

  template: `<div>
              <label class="form-check-label">
                <input @change="$emit('change', filter.text, $event)" 
                       class="form-check-input" 
                       type="checkbox" 
                       :value="filter.text" 
                       :checked="checked" 
                       name="filters"> {{filter.text}}
              {{$props | json 2}}</label>
            </div>`,
});

new Vue({
  el: '#app',
  data: {
    filterFacets: [
      { id: 0, text: 'filter_a' },
      { id: 1, text: 'filter_b' },
      { id: 2, text: 'filter_c' },
      { id: 3, text: 'filter_d' },
    ],
    selected: [], // How can I ensure this contains ['filter_a', 'filter_b'] etc. when selected?
  },
  methods:{
    onChange(filter, $event){
      if ($event.target.checked)
        this.selected.push(filter)
      else {
        const index = this.selected.findIndex(f => f === filter)
        if (index >= 0)
          this.selected.splice(index, 1)
      }
    }
  }
});

Make sure to update your template accordingly:

<div id="app">
  <facet-filter
    v-for="item in filterFacets"
    v-bind:filter="item"
    v-bind:checked="selected.includes(item.text)"
    :key="item.id"
    @change="onChange"
    >
  </facet-filter>
  <p><pre>data: {{$data | json 2}}</pre></p>
</div>

Check out the revised example.

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

Modify the content of a separate division by selecting a different item in a list with the help of Vue.js and TypeScript

I am still learning Vue and may not have all the answers. Currently, I am working on a feature that changes the text of another div based on the item I select from a list. You can find the code sandbox link below along with my current implementation. Code ...

Angular implementation of checkboxes to streamline data filtering

I am currently displaying FreeEvents using a checkbox and passing the value to the filter as filter:filterFreeEvent, which is working perfectly fine. However, I would like to avoid passing the value in the filter and instead use a change event of a checkb ...

When working with Sequelize, you can establish a constraint in SQL Server that allows you to set column A only when column B is null, and vice

Searching for a solution that has already been discussed, I found this thread: Sql Server - Constraint - Allow to set column A only if column B is null and vice-versa However, applying this in sequelize seems to be a challenge. While sequelize offers a v ...

Using JavaScript, display JSON data retrieved from a PHP file

Currently, I am in the process of developing a web application that displays tweets based on a city inputted by the user through an HTML form. The city value is stored in the $_SESSION['city'] variable after the form is submitted. Subsequently, ...

Issue with PrimeNG Carousel width on mobile devices

Currently, I am in the process of developing a system interface with Angular and PrimeNG specifically for mobile devices. The main requirement is to have a carousel to display a set of cards. After evaluating different options, I decided to utilize the ngP ...

The standard flow of work in ReactJS

Exploring the world of ReactJS for the first time has been an exciting journey. I am diving into the basic workflow of this library, along with React Router, without involving Redux. While the learning curve is relatively fast, I find myself encountering c ...

Searching for matching strings in jQuery and eliminating the parent div element

Here's an HTML snippet: <div id="keywords"> <div id="container0"> <span id="term010"> this</span> <span id="term111"> is</span> <span id="term212"> a</span> <span ...

Nuxt.js | Issue with accessing property from computed method's return object

I have been using the computed method to dynamically assign variables and load my page. I am able to display the entire object, but encountering an issue when trying to display a single property. The error message that I receive is: Cannot read property ...

What is the best way to switch focus to the next input using jQuery?

Currently, I am implementing the autocomplete feature using jQuery and everything seems to be functioning properly. The only issue I've encountered is with Internet Explorer (IE) - when a user selects an item from the autocomplete list, the focus does ...

"Exploring the power of NodeJS with createServer, dealing with

Can instances of global.request potentially collide in this NodeJS scenario? I have a basic web server set up in NodeJS where I am globally exposing the request that is created: http.createServer(function(req, res) { global.request = req; // do ...

How to Merge Items within an Array of Objects Using Typescript?

I'm currently facing a challenge in combining objects from an array of Objects in typescript. The structure of the array is as follows: 0: {type: 'FeatureCollection', features: Array(134)} 1: {type: 'FeatureCollection', features: ...

The mysterious case of the missing currentUserObj in Angular with rxjs Subject

I've encountered an issue while trying to pass data from my login component to the user-profile component using an rxjs subject. Despite calling the sendUser method in the login component and subscribing to the observable in the user-profile component ...

`In HTML, trigger blocks based on the number chosen by the user`

I am working on creating a web page where users can select the number of friends they have, and based on that input, a corresponding number of invisible boxes will be triggered. For example, if a user selects 3 friends, 3 boxes will appear for them to ente ...

The Next.js router translates query parameters into encoded format when using the router.push

I'm attempting to create a redirect using router.push in order to include a query string. However, when I try to pass a special character like a comma as part of the parameter value, it encodes my URL. Can you actually include ',' in a URL u ...

Every third item is selected using a JQuery selector

Currently, I am tackling the task of working with PHP loops to generate multiple li elements within a single ul. The issue arises when I attempt to display every fourth li upon clicking one of the preceding three li. My current implementation only toggles ...

Numbering Tables Effectively in ReactJS

Currently working on coding a table in ReactJS and MUI, my goal is to number the No. column from 1 to the length of the array. This snippet shows my code: <TableBody> {quizes.map((quiz, index) => ( <TableRow key={quiz._id}> ...

Tips for tracking advertisement views and saving them in a database

We recently placed our website advertisement on 2 different websites and are interested in tracking the number of clicks or hits we receive from those ads. We would like to store this data in our database. Can anyone suggest a method for accomplishing th ...

Summing values in es6 (TypeScript) without explicitly knowing their corresponding keys

I am facing a challenge with an object that has changeable keys, which I do not want to rely on. The keys in this object are not fixed. Here is an example: interface Inf { [key: string]: number } const obj: Inf = { '2020-01-01': 4, '2 ...

Entering _this

I am encountering an issue with my typescript file where it is failing TSLint. I need some help resolving this problem. The structure of the object in question is as follows: export default class Container extends Vue { // methods doSomething() { ...

Inaccurate Error Handling in Try-Catch Blocks

I am facing an issue with my try-catch block designed to handle errors when connecting to a Mongo Database. Even though I have implemented error handling, Express crashes in the backend when the MongoDB engine is turned off for testing purposes. Is there ...