The onChange Event triggers only once in a checkbox input

I am implementing a checkbox component that emits an event to the parent component. However, in the parent component, I am facing an issue where I need to perform different actions based on whether the checkbox is checked or not, but it seems to only work for the first change.

Checkbox Component:

<template>
  <input
     type="checkbox"
     :checked="ischecked"
     @change="$emit('input', !ischecked)"
   />
    </template>

<script>
    props: {
      checked:{
         type: Boolean,
         default: false
      }
    },
    computed: {
        ischecked(){
          // Some checks with the checked prop, will return true or false
        }
    }
</script>

Parent Component

<template>
 <checkbox-component
     v-for="index in arrayOfData"
     :checked="index.checked"
     @input="test"
  />
</template>

<script>
   (...)
   methods: {
     test:{
       alert('change')
     }
   }
</script>

The issue lies in the fact that the alert message only appears during the initial change of the checkbox state. How can I ensure that it reacts to all subsequent checks and unchecks?

I attempted to use v-model on the parent component, but it disregards the initial value (index.checked) and relies solely on the component data. Unfortunately, setting my data property equal to index.checked is not feasible as index.checked is only accessible within the v-for loop.

Answer №1

To apply two-way data binding on the checkbox-component, ensure that you pass the value as props to the child component for reactivity. Then, bind the checked property of the checkbox-component to this prop value and emit the current checked status by using $event.target.checked like so:

Vue.component('checkbox-component', {
  template: `<input type="checkbox" 
      :checked="value" 
      @change="$emit(\'input\', $event.target.checked)" 
    />`,
  props: ['value']
})

new Vue({
  el: "#myApp",
  data: {
    arrayOfData: [{
      id: 1,
      checked: true
    }, {
      id: 1,
      checked: false
    }]
  },
  methods: {
    test() {
      console.log('change')
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="myApp">
  <div v-for="index in arrayOfData">
    <checkbox-component v-model="index.checked" @input="test"></checkbox-component>
    <label>  {{ index.checked }}</label>
  </div>
</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

search through an object to find specific data

Here is a JavaScript object that I have: var data = { "type": [ "car", "bike" ], "wheels": [ "4", "2" ], "open": [ "Jan", "Jan" ] ...

The issue in AngularJS 1.4 where the select element value is not binding due to a type mismatch

My ng-model has a value assigned to it, but it is not binding with the selected element. <select data-ng-model="myval"> <option value="? number:2 ?"></option> <option value="2" class="ng-binding">Value 1</option> <op ...

"Encountered a Chrome RangeError: The call stack size limit was exceeded while utilizing jQuery's $

As part of my job, I am currently evaluating a web application that involves fetching a substantial amount of data from the server. The data is received as a JSON object using the $.ajax function. It contains numerous sub-objects which I convert into array ...

Modifying the state object in ReactJS: A step-by-step guide on updating values

Below my query and explanation, you will find all the code. I am currently attempting to update the state in a grandparent class. This is necessary due to file-related reasons, and I am using Material-UI for text boxes. Additionally, I am implementing Red ...

Thymeleaf causing Spring IO POST form to redirect to incorrect URL

One of the challenges I'm facing while coding a website is with a form for uploading files. Ideally, when accessing the URL http://localhost:8080/uploadRevision/{docId}, it should lead to http://localhost:8080/uploadRevisionLanding and then redirect b ...

What is the best way to implement authentication on a Vue component in Vue.JS 2?

My view blade appears as follows: @if (Auth::user()) <favorite :id="{{ $store->id }}"></favorite> @else <a href="{{url('/login?red='.Request::path())}}" class="btn btn-block btn-success"> <span class="fa f ...

Using buttons as spinners for input elements with identical styles but unique identifiers

Currently, I am in the process of developing a project that involves users. In order to display all users, I am executing a query on an SQL database. After styling the interface, I have added an input element beside each user, which initializes at zero. Ad ...

Troubleshooting Async Function compatibility between Express and NestJs

Initially, I set up a small express server to handle report generation and file writing tasks. var ssrs = require('mssql-ssrs'); var fs = require('fs'); const express = require('express') const app = express() const port = 30 ...

Is it possible that ngChange does not trigger when the model is updated through code?

According to the documentation, the ngChange directive will not trigger if the model is updated programmatically rather than through a change in the input value. Does this imply that once you programmatically modify the model, you are unable to utilize ng ...

Sending an array of functions to the onClick event of a button

Having difficulty with TypeScript/JavaScript Currently working with an array of functions like this private listeners: ((name: string) => void)[] = []; Successfully adding functions to the array within another function. Now looking to trigger those ...

Having trouble with changing the state within an AngularJS (Ionic Framework) controller?

My goal is to switch views within the Search controller after receiving search results from the server through $http. However, my current approach doesn't seem to be working as intended. I also need to pass the response to the new view for displaying ...

In Backbone.js, specialized events are dispatched to cater to unique needs

In search of a sleek JavaScript animation to have some balls gracefully moving within a canvas, I aim to implement collision detection using custom events managed through Backbone.js rather than resorting to an intricate nested loop to monitor interactions ...

Clicking on a jQuery element will reveal a list of corresponding elements

I've retrieved a list of elements from the database and displayed them in a table with a button: <a href="#" class="hiden"></a> To show and hide advanced information contained within: <div class="object></div> Here is my jQ ...

Struggling to Enforce Restricted Imports in TypeScript Project Even After Setting baseUrl and resolve Configuration

I am facing challenges enforcing restricted imports in my TypeScript project using ESLint. The configuration seems to be causing issues for me. I have configured the baseUrl in my tsconfig.json file as "src" and attempted to use modules in my ESLint setup ...

Exploring Cypress for VUE component testing: Utilizing component access methods

During my work on incorporating a test for components in cypress, I have been contemplating whether it is feasible to access the functions or data of the tested component. ...

AngularJS unit testing with $httpBackend is impacted by conflicts with UI-Router

Here is a controller that utilizes a submit function: $scope.submit = function(){ $http.post('/api/project', $scope.project) .success(function(data, status){ $modalInstance.dismiss(true); }) .error(function(data){ ...

Saving the current language (i18n) in local storage using VueJS

I'm working on a Vue app that utilizes Vue Routers and the Vue $i18n plugin. Here's how I've structured my HTML: <div class="locale-changer"> <select v-model="this.$i18n.locale" class="btn"> ...

AngularJS property sorting: organize your list by name

I have a complicated structure that resembles: { 'street35':[ {'address154': 'name14'}, {'address244': 'name2'} ], 'street2':[ {'address15& ...

Arrange fixed-position elements so that they adhere to the boundaries of their adjacent siblings

Is there a way to keep two fixed elements aligned with their sibling element on window resize? <div class="left-img"> IMAGE HERE </div> <!-- fixed positioned --> <div class="container"> Lorem ipsum... </div> <div class=" ...

Troubleshooting: jQuery addClass() function not functioning properly in conjunction with attr("href", something)

I am trying to implement a unique feature for a link using a Bootstrap button, where it only works on the second click. On the first click, the appearance of the link should change slightly. To achieve this, I am utilizing the .addClass(newClass), .removeC ...