What is the reason for the checkboxes in vuejs not being rendered with the checked attribute set

When working on an edit form, I encountered a situation where I had multiple options to choose from. These options were fetched via ajax using axios and assigned to the variable permisos in the component. Later, these options are rendered through a v-for loop. The selected elements are stored in an array called selected which is then linked to the vue-model as shown below:

<div class="row">
  <div v-for="permiso in permisos" class="col-md-5 col-12 col-sm-5" >                       
      <input type="checkbox" :value="permiso.id" 
         class="form-control" :id=permiso.id
         v-model="selected" :checked=selected.filter(e => e.id === permiso.id).length > 0 > {{ permiso.name}}
  </div>
</div>

Subsequently, another ajax call is made to retrieve the previously selected options before editing the item, so that the appropriate checkboxes can be pre-selected. This is where I'm facing issues with the checked attribute not being set correctly.

axios.get('api/allpermisos')
  .then(response =>{
    this.permisos = response.data; //dataok
  })
if(this.action===2){
  axios.get('api/allpermisos/'+ this.dataobject.id)
    .then(response =>{
        this.selected = response.data;//data ok
    })
}

I am looking for a way to automatically assign the checked attribute when receiving the ajax call with the already selected options, and leave unchecked those that are not selected. I tried using includes but did not achieve the desired outcome. Why does the code work fine when the v-model is removed? What could be causing this issue?

<input type="checkbox" :value="permiso.id" class="form-control" 
        :id=permiso.id  :checked=selected.filter(e => e.id === permiso.id).length > 0 > {{ permiso.name}}

Answer №1

Using both v-model and :checked is redundant. v-model facilitates two-way data binding.

Link to JSFiddle example

<div v-for="permission in permissions" class="col-md-5 col-12 col-sm-5" >                       
    <input type="checkbox" :value="permission.id" 
       class="form-control" :id=permission.id
       v-model="selected"> {{ permission.name}}
</div>

It's advisable to create a component for your input. Managing form inputs within a v-for loop can quickly become complex.

Answer №2

Make sure to store the ids in the "selected" array, as it seems storing whole objects isn't effective based on my observation.

HTML:

<div id="app">
  <div class="row">
    <div v-for="permiso in permisos" class="col-md-5 col-12 col-sm-5" >                       
        <input type="checkbox" :value="permiso.id" 
           class="form-control" :id=permiso.id
           v-model="selected" :checked=selected.includes(permiso.id)> {{ permiso.name}}
    </div>
  </div>
</div>

Vue:

new Vue({
  el: '#app',
  data() {
    return {
      selected: [2, 4],
      permisos: [{id: 1, name: "test1"}, {id: 2, name: "test2"}, {id: 3, name: "test3"}, {id: 4, name: "test4"}]
    }
  }
})

https://jsfiddle.net/eywraw8t/15555/

This method is successful. If you receive an object array as a response, you can use the following approach:

this.selected = response.data.map(obj => obj.id);

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

I am receiving a success message from webpack indicating that the compilation was successful, but I am encountering a blank page in the

My app.js looks like this: import Home from "./pages/home/Home"; import Login from "./pages/login/Login"; import Profile from "./pages/profile/Profile"; import Register from "./pages/register/Register"; import { Brow ...

Validating numbers in React JS input fields component

I need assistance with implementing number validation for 3 Textfields in my application. Currently, the code displays an error message if a Textfield is empty, but I am stuck on validating whether the input is text or numbers. import React from 'rea ...

Modify the universal variable through a jQuery action

As a newcomer to jQuery with limited experience in JavaScript, I find myself facing a dilemma. I am working on a jQuery range slider that displays two year values, and I have successfully stored both the minimum and maximum years in a variable. However, I ...

extract individual components from the google books api

It has been quite a while since I last dabbled in JavaScript, so I decided to embark on a project creating a "bookcase" to organize the books I have read and those I still want to read. One challenge I encountered was figuring out how to separate the eleme ...

The information transmitted from the Laravel controller is not syncing with the Vue variable as expected

I've been working on a web app with a dashboard using Laravel and Vue. While passing data from the controller to the Vue file, the data is received correctly. However, when I try to set it to a Vue variable, the value does not update in the variable. ...

How to pass only the clicked element to the onClick function in React.js

I have several elements with the same className, and I want to add the className active to an element (with the className history-node) when it is clicked, in addition to its current className. However, I am facing an issue where the child elements of tha ...

Exploring ways to capture all console outputs or retrieve the current console content in frontend development

Currently working with Angular and looking to integrate a bug reporting feature into my application. I want to capture the content of the browser's console for debugging purposes. However, I'm unsure of how to access it. Not all errors are logge ...

Deliver search findings that are determined by matching criteria, rather than by identification numbers

I am seeking to return a JSON match upon form submission, rather than simply searching for a specific ID. However, I am uncertain about how to structure this. I have the ability to search for the necessary match in a JavaScript document within one of my n ...

Creating a condensed version of the process: Utilizing jQuery for thumbnail preview on hover to create an image slideshow

I've created a video preview slideshow function using jQuery. As a newcomer to jQuery, I'm questioning if there's a more efficient way to achieve this. Having separate timers for each frame feels cumbersome and limits the flexibility in chan ...

Revamp your code by utilizing ES6 class to replace multiple if statements in Javascript

Currently, my code is filled with numerous if statements and I am considering a switch to classes in ES6. However, Javascript isn't my strong suit... so PLEASE HELP ME..! Previous code: //example code function first(){ console.log('first sce ...

When using Vue 3 with Laravel Blade template, issues arise when trying to generate a production build

When working with Vue 3 SFC and trying to embed the template inside a Laravel Blade file, it can be a bit tricky. Take for example this usage scenario: Test.vue <script setup> import { ref} from 'vue'; const testValue = ref('Works&a ...

Navigating to a Different Page in React Based on Button Click and Meeting Specific Conditions

Within this particular component, I have implemented a button named Submit. When this button is clicked, it triggers a series of actions: first, it exports the drawing created by the user as a jpeg URL, then sends this image data to another API that genera ...

Using Nuxt and Cloudinary to seamlessly upload images from the client side directly to the Cloudinary platform

Is there a way to directly upload images from my Nuxt (vue) app to Cloudinary without involving a server? I've been searching for information on how to accomplish this but haven't found any concrete solutions. <v-file-input v-else ...

The element is implicitly imparted with an 'any' type due to the incapability of utilizing an expression of type 'number' to index the type '{}'. This error occurs in the context of VUEJS

I have encountered an issue that I have been struggling to resolve despite trying numerous solutions. The problem arises while working on a project using Vue. Here is how I have structured my data: data(){ return{ nodes: {}, edges:{}, ...

Include a single element repeatedly on a single webpage

Is there a way to add the same component multiple times on one page? I have an input component that receives props and performs certain functions. I need to include more than one instance of this input component on a single page, but when I try to copy and ...

Receiving multiple NodeJS Responses through AJAX for a single request

I have been working on a WebApp that involves heavy AJAX calls from the frontend and NodeJS Express at the backend. Here is a glimpse of my Frontend Code- Below is the global AJAX function I consistently use in all my projects: function _ajax(params = {}, ...

Is there a way to prevent a background video from automatically playing whenever the user navigates back to the home page?

Recently, I was given a design that requires a background video to load on the home page. Although I understand that this goes against best practices, the client has approved the design and now I need to come up with a solution. The video is already in pla ...

The functionality of a Vue custom tooltip behaves strangely after clicking the button multiple times

I created this custom tooltip code that automatically closes after 2 seconds when a user clicks on a button, not just hovers over it. Initially, it works perfectly for the first two clicks, but then starts behaving strangely from the third click onwards. ...

Implementing a method to pass total value to the <td> tag in angular JS using controller

I am having trouble calculating the total IR for each table cell. Despite my efforts, the function is not working as expected and I can't figure out why. $scope.getTotalb = function () { var totalb = 0; for (var i = 0; i < $scope ...

Can you explain the distinction between bodyparser.urlencoded and bodyparser.json?

I'm a bit confused about the use of bodyparser. Why is it necessary when we can simply use json.stringify (to convert an object to a string) and json.parse (to convert JSON to an object)? Is it because by using app.use() with bodyparser, the middlewa ...