Guide on customizing the checkbox label class upon @change event in Vue?

Query: I have a list of checkboxes connected to an array of names. The objective is to alter the class of a specific name when its checkbox is clicked.

Issue: Clicking on a checkbox causes all names to change class, instead of only affecting the one associated with the checkbox.

View the problem in action on JSFiddle: JSFiddle

HTML

<div id="app">
<ul>
 <li v-for="name in names" :key="index"gt;
   <input @click="available = !available" type="checkbox">  
   <label :class="{available:available}" >{{name.name}}</label>
  </li>
</ul> 
</div>

Vue instance

var app = new Vue({
  el: '#app',
  data: {
    available: false,
    names: [{'name':'Jerry'},{'name':'Eddie'},{'name':'Kerry'},{'name':'Jane'}]
  }
})

Css

.available{
    text-decoration: line-through;
}

Answer №1

Assign a variable to each name object and implement a method to update the availability property:

var app = new Vue({
  el: '#app',
  data: {
    names: [
      {'name':'Jerry', 'available': false},
      {'name':'Eddie', 'available': false},
      {'name':'Kerry', 'available': false},
      {'name':'Jane', 'available': false}
     ]
  },
  methods: {
    updateAvailable(index) {
      // Toggle the availability of a specific object based on its index
      this.names[index].available = !this.names[index].available
    }
  }
})

Next, in your template, invoke the updateAvailable method:

<div id="app">
<ul>
 <li v-for="(name, index) in names" :key="index">
   <input @click="updateAvailable(index)" type="checkbox">  
   <label :class="{available: name.available}" >{{name.name}}</label>
  </li>
</ul> 
</div>

Answer №2

Modify the structure of your template by moving the available property into each name element and toggling the name.available. Utilize v-model on your checkboxes for an added functionality.

const names = [{'name':'Jerry'},{'name':'Eddie'},{'name':'Kerry'},{'name':'Jane'}]

const app = new Vue({
  el: '#app',
  data: () => ({
    names: names.map(name => ({ ...name, available: false }))
  })
})
.available {
  text-decoration: line-through;
}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="app">
  <ul>
    <li v-for="(name, i) in names">
      <input :id="`name_${i}`" v-model="name.available" type="checkbox">
      <label :for="`name_${i}`" :class="{ available: name.available }">
        {{name.name}}
      </label>
    </li>
  </ul>
</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

Leveraging JavaScript for setting an ASP.net Dropdownlist

I have made several attempts to set the dropdownlist without success. Despite observing the selectedIndex changing appropriately in developer tools, and noticing the selected option node change from false to true, the dropdownlist still displays the first ...

What is a sleek and stylish method to tally numbers in ascending order?

Is there a way to create a function in JavaScript or PHP that counts smoother than simply adding numbers together? For example: If we have 53 + 39, the result would instantly be 92. But instead of this instant calculation, I want the count to go from 0-1 ...

Identify the initial ul element and modify the contents of the li within it, or generate a new li using jQuery's

Is there a way to identify the first, second, or third ul element within a particular div or form? I am looking to modify the li elements in the second ul as soon as a ul is detected on the page. var ulCountFood = $('#nl-form').find('ul&apo ...

Leveraging the results from a static React function

I am currently working on a React + Webpack project that supports JavaScript ECMAScript 6. Here is the code snippet I am trying to implement: class ApiCalls extends React.Component{ static uploadFiles(files) { // upload code if(success) { ...

Using Redis for caching in Node.js applications

As I delved into this module, I found myself pondering the use of callbacks within it. My understanding is that memory caching is designed to be speedy, providing instant results. So why introduce callbacks, which may imply a waiting period? If the resul ...

I am attempting to insert the following script to display a list of products, but after adding it, the menu bar seems to be malfunctioning

Can you help with an issue regarding the menu bar's functionality? The code snippet below is meant to list some elements but seems to be causing problems with the menu bar. <script type="text/javascript" src="http://code.jquery.com/jquery- ...

Using a UUID as the default ID in a Postgres database system is a straightforward process

As I transition to postgres from mongodb due to the recent announcement, I've noticed that the IDs are simply numerical and auto-incremented. I've attempted a few solutions: Setting the default ID to a UUID with a lifecycle hook - Unfortunately, ...

Successful execution occurring prior to beforeSend in a Cordova iOS application utilizing jQuery Ajax

After making some changes to the HTML of the login button, I encountered an issue where the alert was being triggered before the button's HTML had updated when testing on my iPhone using a Cordova-built app. Strangely, this problem did not occur when ...

Tips for embedding a hyperlink in your HTML website

While I've mastered adding images to my HTML website, there's one thing that still eludes me despite scouring numerous online resources. I recently created a small animation using JavaScript on a different IDE, and I have the link to my output: ...

Keeping an object in a multidimensional array based on its ID in Angular 4/Ionic 3 without removing it

Exploring a complex data structure: [{ propertyoutsideid: 1, items: [ {itemId: 1, something: 'something'}. {itemId: 2, something: 'something'}. {itemId: 3, something: 'something'}. ] },{ prope ...

Issue with SoundCloud Javascript SDK 3.0 failing to execute put methods

Currently, I am developing a service that utilizes the SoundCloud Javascript SDK 3.0, and I seem to be encountering issues with the PUT methods. Every call I make results in an HTTP error code of 401 Unauthorized. Below is my JavaScript code, which close ...

What steps are involved in integrating Bootstrap and jQuery into a Vue Webpack-Simple template?

I am trying to integrate Bootstrap 3 into my Vue app. Here is what I have done so far: vue init webpack-simple npm install jquery bootstrap After this, I added the following to webpack.config.js: module.exports = { ... plugins: [ new webpa ...

Issue with Angular-cli: typescript files not being generated when using the --dev option

Currently using angular-cli version 1.0.0-beta.14 with node version 6.6.0 on a Windows 32 bit x64 operating system. This setup utilizes the webpack version of angular-cli and I can successfully use ng build to compile. The output of ng build indicates that ...

When the Navbar div is set to Position:fixed, it generates empty space on the page

I'm facing the issue of unwanted white space in the center of the page below the Navigation Bar. Despite numerous attempts to remove it, I haven't been successful. Below is the HTML code snippet: html: <!DOCTYPE html> <html> <h ...

Adjusting the placement of a dropdown menu while scrolling within the container element using CSS

Is there a way to keep the submenu aligned under the button even when scrolling within the container div? Currently, it stays in the middle of the page. div.container { height: 200px; width: 400px; border: 1px solid black; overflow-y: scroll; ...

Tips for extracting nested information from a firebase real-time database

Recently, I created a small website where my family and friends can place their bets on the name, gender, and date of birth of our upcoming baby. To make this happen, I utilized Vue along with Firebase's real-time database. Now, I am looking to develo ...

What is the best way to retrieve user roles in order to access all instructor posts within my MERN application?

There are 2 models in my code: Post and User. import mongoose from 'mongoose'; const PostSchema = new mongoose.Schema( { title: { type: String, required: true, }, text: { type: String, required: true, ...

How to achieve the functionality of multiple inheritance using Object.create()

Seeking insights on implementing multiple inheritance in JavaScript. Various methods exist, each with pros and cons. However, there lacks a comprehensive analysis of Object.create() presented in an understandable manner. After conducting experiments, I hav ...

Unable to establish cookie via frontend React application

I am currently working with a backend node server that offers two APIs, one to set cookies and another to get cookies. Here is the backend code for setting and retrieving cookies: Server : localhost:4001 router.get("/addCartToCookie", function( ...

Tips for creating a multi-line text field with ellipsis using a div in CSS

Similar Question: How to Insert Ellipsis in HTML Tag for Content that is Too Wide Using CSS to Display “…” on Overflowing Multiline Blocks Hello, I am attempting to create a div tag to present a question. The size of this div bo ...