monitoring checkbox status in vue?

When using Vue, I have created dynamic checkboxes that display as shown below:

<li v-for="element in checklist" :key="element.id" class="block w-full p-1">
            <div v-if="element.taskId == task" class="w-full border-2 rounded-md p-4">
              <div class="float-right">
                <button @click="deleteCheck(element.id)">
                  <Trash2Icon class="px-1"/>
                </button>
              </div>
              <div class="flex">
                <input type="checkbox" id="checkbox" v-model="element.checked" class="w-6">
                <label for="checkbox" class="px-2">{{element.content}}</label>
              </div>
            </div>
          </li>

I am trying to utilize the "element.checked" value with a watch() function in Vue to send it to an API using axios. Here's what I have attempted:

watch: {
 element.checked() { // This part is not working as intended
  axios.put('api/blabla' + element.id, // Unsure about this line, just testing
   checked: this.element.checked
  })
  .catch(err => {
     console.log(err)
  })
 }
}

I am open to exploring different methods aside from the one mentioned above. The error occurs when accessing element.checked.

For reference, my checklist data structure is:

"checklist": [
    {
      "content": "lorem ipsum dolor",
      "checked": true,
      "id": 1
    },
    {
      "content": "lorem ipsum dolor sit",
      "checked": false,
      "id": 2
    },
]

Answer №1

If you want to avoid using a watch function in this scenario, simply bind a @change event like so:

<input type="checkbox" id="checkbox" v-model="element.checked" @change="customMethod" class="w-6">

Then, within your methods section:

methods: {
customMethod() {
  axios.put('api/blabla' + element.id,
   checked: this.element.checked
  })
  .catch(err => {
     console.log(err)
  })
}

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

Tips for ensuring the security of your code in node.js

Here is a snippet from my app.js that deals with managing connections: var connections = []; function removeConnection(res) { var i = connections.indexOf(res); if (i !== -1) { connections.splice(i, 1); } } I make a call to removeConn ...

Simultaneous Checking of Two Checkboxes in a Single Row

I came across a similar question that was answered in this link. However, I am looking for a way to only check the checkbox next to another checkbox. Here's an example: +-------------------------------+ |column1 | column2 |column3 | +----------- ...

Tips for retrieving items from <ng-template>:

When the loader is set to false, I am trying to access an element by ID that is located inside the <ng-template>. In the subscribe function, after the loader changes to false and my content is rendered, I attempt to access the 'gif-html' el ...

Is it possible to determine if the process for changing Three.js material has been successfully completed?

Is it possible to determine the completion of this process? material.map = new THREE.Texture( canvas ); material.map.needsUpdate = true; If not, sometimes the final result will be a black snapshot. var snapshotData = renderer.domElement.toDataURL(strMi ...

Execute the code only if the variable is not null

I encountered an issue with my code: setInterval(function() { $.ajax({ url: url, success: function(data, count){ var obj = jQuery.parseJSON(data); var content = obj.results[0].content; }}) }, 2000) The code runs every 2 seconds an ...

Organizing an array of objects within MUI cards based on social media platforms

I'm currently developing an application that showcases athlete data in a grid layout using MUI Grid. The colored borders on the left side of each card are determined by the corresponding social network associated with that athlete. https://i.sstatic. ...

The error message "There is no defined window.matchMedia prefers-color-scheme window in Next.js"

I am currently working on a project with React.js alongside Next.js and encountered an issue that I need assistance with. Upon loading the page, I need to set a variable that indicates whether the user is using dark mode or not. I attempted the following ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

Creating a file logging system with console.log() in hapi.js

I have recently developed an Application with Hapi.js and have utilized good-file to record logs into a file. However, I am facing an issue where the logs are only written to the file when using request.log() and server.log() methods. My goal is to also lo ...

Spring Boot fails to recognize path variable data sent from Angular

When working with Angular 7, I encountered a situation where I needed to pass a value from the service class of Angular. Here is how I achieved it: executeHelloWorldBeanServiceWithPathVariable(name){ console.log("name coming from here"+name); retu ...

Mastering the Art of Promises in RXJS Observables

After thoroughly researching SO, I stumbled upon numerous questions and answers similar to mine. However, I suspect that there might be gaps in my fundamental understanding of how to effectively work with this technology stack. Currently, I am deeply enga ...

Harness the power of ng-click in conjunction with data-ng-href for a

I am attempting to create a button that takes the user to the product details while also having the ability to increase a counter using an ng-click function. <div class="row center-block save-button" > <a data-ng-href="/savings/{{saving._id}} ...

What is the method for storing API status JSON in the state?

Can anyone help me figure out why the json in the register state is returning an empty object after console.log(register); from that state? import React, { useEffect, useState } from "react"; import { Formik } from "formik"; // * icons ...

Guide to embed a Google Sheets chart into a WordPress website

I'm looking to include a chart in a wordpress post, using the script generated from google sheets' publish function. When I add the script to a generic HTML page, the chart displays properly. However, when I insert it into a wordpress post, I en ...

Submit a set of form variables to PHP using AJAX

I am attempting to transmit a set of form parameters to a PHP script for processing. In the past, I have achieved this using $.post, but now my goal is to accomplish it exclusively with $.ajax. Below is the jQuery click event designed to send all variabl ...

No response headers retrieved from WebAPI

Currently, I am utilizing the ASP.NET WebApi in conjunction with a ReactJs application on the front end. In this scenario, I am working on implementing a Get method that enables file downloads from the server. My objective is to configure both the Content- ...

Sending colored output from stdout to grunt's output stream

Having trouble creating a custom grunt task that runs mocha tests and displays colored output? I'm running into an issue where grunt is stripping out the colors from the mocha command's output. Here's the code for the grunt task: var exec = ...

angularJS editable input field with click-to-exit functionality

One issue I encountered involved an editable text field directive in Angular, which is structured like this: myApp.directive('editable', function () { return { restrict: 'E', scope: { model: '=&apos ...

Resposiveness of force-directed graph is lost

const container = document.getElementById("container"); const svgElement = d3.select(container).append("svg") // Get the width and height computed by CSS. let width = container.clientWidth; let height = container.clientHeight; const colorScale = d3.scale ...

Setting up Redis for session store in the right way involves a few key steps

I have been attempting to configure Redis Store in the following manner: var express = require('express'); var app = express(); ....... ....... var session = require('express-session'); var redis = require("redis").createClient(); var ...