Trouble encountered while attempting to utilize @click="checkedInput" for displaying checkbox label in Vue.js?

const app = new Vue({
  el: '#app',
  data: {
    checkedNames: [],
    checkedName: true,
    close: false
  },
  methods: {
    uncheck(checkedName) {
      this.checkedNames = this.checkedNames.filter(name => name !== checkedName);
    },
    uncheckall(event) {
      this.checkedNames = [];
    },
    mouseOver() {
      this.close = true;

    },
    mouseOut() {
      this.close = false;
    },
    checkedInput(event) {
      if (this.checkedNames.includes(event.target.value)) {
        this.uncheck(event.target.value)
      } else {
        this.checkedNames.push(event.target.value)
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<div id='app'>
  <ul class="checkboxes">
    <li><input type="checkbox" id="jack" value="Jack" @click="checkedInput">
      <label for="jack">Jack</label></li>

    <li><input type="checkbox" id="john" value="John" @click="checkedInput">
      <label for="john">John</label></li>

    <li><input type="checkbox" id="mike" value="Mike" @click="checkedInput">
      <label for="mike">Mike</label></li>
  </ul>
  <br/>
  <ul class="tags">
    <li @mouseover="mouseOver" @mouseleave="mouseOut" @click="uncheck(checkedName)" class="badge badge-pill badge-primary" v-for="checkedName in checkedNames">
      {{ checkedName }}<span v-show="close" aria-hidden="true">&times;</span>
    </li>
    <li class="badge badge-pill badge-danger" @mouseover="mouseOver" @mouseleave="mouseOut" @click="uncheckall" v-show="checkedNames != ''">Clear</li>
  </ul>
</div>
However, I need to address a small issue with the code without using v-model. The problem seems to lie within the checkedInput method. Upon further testing, I found a bug in the implementation. After selecting a checkbox, it correctly displays the selected checkbox label. However, clearing the selection by clicking on the label does not uncheck the checkbox. Additionally, when all checkboxes are selected and cleared using the "Clear" button, the checkboxes remain checked. Manually unchecking the checkboxes also results in errors where only one label is displayed and the second checkbox label is not updated.

Answer №1

Implementing v-model simplifies the process. Here is an updated solution with some restructuring:

new Vue({
  el: '#app',
  data: () => ({ checkedNames: [], close: false }),
  methods: {
    uncheck(checkedName) { this.checkedNames = this.checkedNames.filter(name => name !== checkedName); },
    uncheckall() { this.checkedNames = []; },
    mouseOver() { this.close = true; },
    mouseOut() { this.close = false; }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<div id="app">
  <ul class="checkboxes">
    <li>
      <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
      <label for="jack">Jack</label>
    </li>
    <li>
      <input type="checkbox" id="john" value="John" v-model="checkedNames">
      <label for="john">John</label>
   </li>
    <li>
      <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
      <label for="mike">Mike</label>
    </li>
  </ul>
  <br/>
  <ul class="tags">
    <li 
      v-for="(checkedName, checkedNameId) in checkedNames"
      :key="checkedNameId"
      @mouseover="mouseOver" 
      @mouseleave="mouseOut" 
      @click="uncheck(checkedName)" 
      class="badge badge-pill badge-primary" 
    >
      {{ checkedName }}<span v-show="close" aria-hidden="true">&times;</span>
    </li>
    <li 
      class="badge badge-pill badge-danger" 
      @mouseover="mouseOver" 
      @mouseleave="mouseOut" 
      @click="uncheckall" 
      v-show="checkedNames.length"
    >
      Clear
    </li>
  </ul>
</div>

MODIFICATION:

If you prefer not to opt for the previous solution, your current method faces a challenge as the array checkedNames lacks two-way binding with the inputs, leading to unreflected changes on the template. To tackle this, preload it and utilize v-for to display checkboxes that can adjust the checked attribute of each item. Additionally, generate labels below by creating a computed property listing the selected items:

new Vue({
  el: '#app',
  data: () => ({ checkedNames: [ { id:1, name:"Jack", checked:false }, { id:2, name:"John", checked:false }, { id:3, name:"Mike", checked:false } ], close: false }),
  computed: {
    checkedLabels() { return this.checkedNames.filter(({ checked }) => checked === true); }
  },
  methods: {
    uncheckall() { this.checkedNames.forEach(item => item.checked=false); },
    mouseOver() { this.close = true; },
    mouseOut() { this.close = false; },
    checkedInput(checkId) {
      const item = this.checkedNames.find(({ id }) => id === checkId);
      item.checked = !item.checked;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<div id='app'>
  <ul class="checkboxes">
    <li
      v-for="({ id, name, checked }) in checkedNames"
      :key="id"
    >
      <input 
        type="checkbox" 
        :id="name" 
        :value="name" 
        :checked="checked" 
        @click="checkedInput(id)"
      >
      <label :for="name">{{name}}</label>
    </li>
  </ul>
  <br>
  <ul class="tags">
    <li 
      v-for="({ id, name}) in checkedLabels"
      :key="id"
      @mouseover="mouseOver" 
      @mouseleave="mouseOut" 
      @click="checkedInput(id)" 
      class="badge badge-pill badge-primary" 
    >
      {{ name }}<span v-show="close" aria-hidden="true">&times;</span>
    </li>
    <li 
      class="badge badge-pill badge-danger" 
      @mouseover="mouseOver" 
      @mouseleave="mouseOut" 
      @click="uncheckall" 
      v-show="checkedLabels.length"
    >Clear</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

Choose Status Menu DiscordJS version 14

Is there a way to get help with changing the bot's status if it's not working properly? The value of the variable "statuses" is set as status, but the status itself does not change. Using client.user.setStatus('dnd'); can sometimes work ...

Show the JSON data returned

Looking for a way to display the JSON response in a JSP page using AJAX... function doAjaxPost() { var name = $('#name').val(); var password = $('#password').val(); var gender = $('#gender').val(); var abo ...

Reconfigure the API to segment its components into individual variables

I'm currently working with an API that offers a wide range of available calls. In my VUE code, I am looking to modify it so that depending on which button is clicked, a different call is triggered. You can check out one example of this here: <> ...

Issue with using Javascript variables within Highcharts

I am facing an issue with displaying a high charts pie chart dynamically. When I pass the exact value format into the data index in the high chart, it doesn't show anything in the chart. However, if I directly assign a value to a variable, it works fi ...

Why does my JavaScript code fail to retrieve input values?

When the button labeled click here is clicked, it will trigger an alert with empty values. I am curious why the alert does not display the values 400 and 400. This code snippet is from test1.php: <script src="https://ajax.googleapis.com/ajax/libs/jqu ...

The issue I am encountering is that the value from jQuery autocomplete is not getting transferred to the

I'm having trouble retrieving a textInput from a Form where I am extracting values from Jquery Autocomplete. The selected value is not being transferred to the form. Can you please help me identify what I am missing? $(function() { var availableT ...

Encountering an Ajax Issue with Laravel 5.4

I encountered the following error: "{"status":"error","msg":"Category was not created"}" Below is my Controller Function where I execute the action : function create_category(Request $request){ if($request->ajax()){ $c ...

Update individual component based on selected value

I am working on a blogs page that consists of two main components: filter and card <template> <div> <div v-if='$apollo.loading'>Fetching data...</div> <div v-else> <FilterComponent :categorie ...

How can a button be linked directly to a particular list item?

I currently have a HTML tag within my React application that looks something like this: <ul> <li> Item 1 <button> Delete </button> </li> <li> Item 2 <button> ...

What is the best way to transform object request data into a string in an Express application using Node.js

I am trying to save the request data from app.get('/') to a variable, but I keep getting an error "TypeError: Converting circular structure to JSON". var express = require('express') var app = express() var bodyParser = require('b ...

Is there a way to set the default timezone for the entire application to something like 'UTC' using JavaScript and Angular?

I'm currently developing a Hotel application where customers communicate using UTC. I have completed most of the work but everywhere I used the date object like so => new Date(). Before running the application, I need to change my local timezone to ...

It's next to impossible to secure expedited work on an ongoing project using Vercel

Yesterday, I successfully deployed an application on Vercel using only ReactJS. Today, I made the decision to develop an API for my application, To clarify, I have a folder housing the React app, and within that, I created a directory named "api" followi ...

Get an Array Using AJAX in PHP and JavaScript

Section 1 I want to retrieve an Array from PHP and use it in JavaScript. I have created a file using the fwrite function in PHP, then included that file in my next .load method inside a Div. The new PHP file contains an "include 'somefile.php';" ...

Is there a way to retrieve the present value of a dropdown menu once an ajax call is successful?

Currently, I am facing an issue where I am unable to retrieve the selected value from a dropdown menu. The logged value is always the first option in the dropdown menu, even though I have set it to a different value. Can someone help me identify what I may ...

Activate a button by simulating a click event through a shortcut key with the help of a

I have incorporated the hotkeys plugin to enable shortcut functionality on my website. Currently, I am looking for a way to automatically trigger a button click when any shortcuts are pressed. hotkeys.add({ combo: 'alt+1', callback: function (da ...

Steps to enable overflow: 'scroll' for components generated dynamically

When developing a React application, I encounter an issue with creating new components dynamically inside a container. The problem arises when the height of the container gets exceeded by the newly added items, and I aim to make the container scrollable in ...

The maximum number of $digest() iterations (10) has been exceeded in $rootScope. Exiting the process

Using UI-Router, I need to check the existing token every time a state change is initiated. The issue only occurs on the initial page load, and disappears upon refreshing the page. Below is the code snippet that I suspect might be causing the error: .run ...

Issues with running Vue commands have been reported in Git-Bash, however they seem to work fine in

Whenever I check the version of Vue in my Terminus bash by running vue --version, here's the output I receive: $ vue -v /bin/sh: /Users/kirkb/AppData/Local/Yarn/bin/../Data/global/node_modules/.bin/vue: No such file or directory In PowerShell, when I ...

JavaScript: Troubleshooting Array Formatting

Seeking assistance with formatting this JavaScript array accurately. It seems like I am overlooking something crucial: Javascript: <script type="text/javascript"> var dimensions = new Array("225","320","480", "--"); var walls = new Array() ...

Can a React component be configured to show only a specific array key when returning an array?

Just diving into the world of react and experimenting with different approaches to understand how I can transition into this new architecture. Currently, I have a basic component where I am returning an array of elements (mainly for testing purposes): cl ...