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

When the value remains unchanged, Angular's @Input() value does not get updated

Upon running this program, I initially receive the output as false, 5, 500 since they have been initialized in the child component. However, upon clicking the update button, I am unable to revert to the previous values. Instead of getting true, 10, 1000, I ...

Maintain consistent spacing after receiving a value

I have a content editable span where you can write whatever you want. For example: Hello, My name is Ari. However, when I try to retrieve the text and alert it using my program, it displays without any line breaks or spacing like this: "Hello,My name is ...

Retrieve the texture's color based on the UV coordinates

Currently, I'm working with version 73 of V. I am dealing with UV coordinates obtained from the intersection of a raycaster and a texture of an object. Is there a way to extract the color (RGB or RGBA) of the used texture at these specific UV coordina ...

What is the process for uploading an image using fetch?

After just starting to learn react, I decided to create a gallery App. However, I am facing an issue when trying to post pictures to the API. Whenever I click on the ADD button, nothing happens except for an error 500 being logged in the console. Below is ...

Using a javascript parameter in a cshtml file to filter data in a datatable

Here is the model code public class viewCase { public List<string> lstCategory { get; set; } public DataTable dtWrkTsk { get; set; } } This is the controller code string query = "SELECT WorkFlowID,Subject,Category FROM CMSTasksWorkFlow" ob ...

Updating Sailsjs Localization Settings

After working with Sails.js for a while, I am interested in finding out if it is possible to manually adjust the localization from the controllers based on the URL. For example, accessing http://example.com/en would display the English version, while http ...

"Learn how to use jQuery to retrieve a specific row from an HTML table based on equality with a certain

I have a dynamically generated table using PHP. The information in this table is related to different semesters (such as first, second, third, etc.). I want to display specific semester information when a user clicks a link from the same table without need ...

Adding JSON data to an HTML document

Seeking guidance on how to efficiently parse and display information from a JSON file consisting of 3 objects onto a widget. Unsure of the best approach to achieve this task. Any suggestions or methods would be greatly appreciated. Widget Structure: < ...

Encountering an error stating "cloudinary.uploader is undefined" while attempting to delete media files from Cloudinary

I'm currently developing a web application using express and node.js. In my project, I'm utilizing cloudinary for uploading media files. While uploading and accessing media works smoothly, I'm encountering an issue with deleting images from ...

Component library for Vue-cli 3 with built-in support for server-side rendering

I am in the process of developing a custom component library that I intend to distribute across various domains. Domains: Each domain is equipped with its own instance of Nuxt Every domain has included my-component-lib in their package.json Additional ...

What is the best way to show nested objects in JavaScript?

let paragraph = document.createElement('p'); document.body.appendChild(paragraph) const fruit = { type: 'Apple', properties: { color: 'Green', price: { bulk: '$3/kg', smallQty: '$4/kg' ...

What is the method for graphing data points that include two different y values?

I have been on the lookout for a solution to this question for quite some time now. While there are a few options that come close, I am yet to find the perfect answer. My goal is to create a line chart displaying water levels over time. I would like the d ...

What causes the child component to re-render when only the prop is changed and useCallback is used?

Child component will only re-render if its prop (numberModifier) is changed. The numberModifier uses useCallback with no dependencies, so it remains constant. To test this, I alter the value of "online" in the Application component which is a prop of Pare ...

CoffeeScript's alert feature appears to be malfunctioning

After stumbling upon CoffeeScript in a blog post, I was excited to try it out. My first attempt at using it involved this code snippet: alert "Hello CoffeeScript!" Unfortunately, it didn't work as expected and produced the following error message: ...

Display scroll bars over the position:absolute header

My container has content that exceeds its size in both directions. To see the issue, try scrolling horizontally and vertically on the table available here: The vertical scrollbar is visible as desired, except that it gets hidden behind the table header un ...

Submitting an extremely large string to an Express server using JS

How can a large String be efficiently sent to a Node.js Express server? On my webpage, I am using Codemirror to load files from an Express server into the editor. However, what is the most effective method for sending "the file" (which is actually a bi ...

Displaying adornments in a vertical arrangement within a TextField using Material UI

Is there a way to display adornments vertically in a Material UI Textfield? I've been trying but it always shows up horizontally. Snippet: <TextField variant="filled" fullWidth multiline rowsMax={7} onFocus={() => h ...

Child component in Vue 3 not updating with passed value

Here's the main template code snippet: {{ filteredResults.length }} <results-count-filters :active-filters="activeFilters" :filtered-results-length="filteredResults.length" @update-filter="updateFilter"></resul ...

Decoding the `this` Mystery in VueJS

Recently, I decided to delve into the world of VueJS starting from square one. Following their official guide has been a helpful resource, but I've hit a roadblock at this section. One particular example in the guide caught my attention... var app5 = ...

@keyframes shimmering-fade

I'm attempting to create a text animation effect (please see video) but I'm struggling to find the solution!! Can someone assist me with this? Should I use JavaScript for a better result? h1.fadeinone { animation: fadeinone 10s;} h1.fadeintwo ...