Guide to selecting a checkbox in Vue.js 2 based on a specific value?

I'm currently working on setting up a roles and permissions system for my application. For the frontend, I am using Vue.js2 and for the backend, Laravel 5.4.

Below is the allRoles array containing all roles fetched from the database:

data: {
    // ...
    allRoles: [],
    userInfo: {
        id: null,
        fullname: '',
        phone: '',
        email: '',
        created_at: '',
        roles: [],
        permissions: []
    },
    // ...
},

Here's the method used to retrieve user information and populate the allRoles array:

getUserInfo(user_id) {
    this.infoLoading = true;
    axios.get(`/api/users/info/${user_id}`)
       .then((response) => {
          console.log(response);   
          if(response.status === 200) {
              this.userInfo.id            = response.data.user.id;
              this.userInfo.fullname      = response.data.user.fullname;
              this.userInfo.email         = response.data.user.email;
              this.userInfo.phone         = response.data.user.phone;
              this.userInfo.created_at    = response.data.user.created_at;
              this.userInfo.roles         = response.data.user.roles;
              this.userInfo.permissions   = response.data.user.permissions;  
              this.updateUserInfoButton   = true;
              this.allRoles               = response.data.allRoles;
              this.allPermissions         = response.data.allPermissions;
          }
          this.infoLoading = false;
      })
      .catch((error) => {
          console.log(error);
      });
}

Checkboxes are not getting checked as expected in the following markup section. How can I correctly achieve this functionality? Any suggestions?

<div class="checkbox checkbox-success" v-for="role in allRoles">
    <div v-for="singleRole in userInfo.roles" :key="singleRole.id">
        <input :id="role.name" type="checkbox" :value="role.id" v-model="userInfo.roles" :checked="singleRole.name.includes(role.name) ? 'true' : 'false'">
        <label :for="role.name">@{{ role.display_name }}</label>
    </div>
</div> 

If you have any insights or alternative approaches to resolve this issue, please let me know. Thanks!

Answer №1

If you are looking to display a list of roles, and have the user's roles checked and updated in userInfo.roles simultaneously, this method should work as long as userInfo.roles contains the ids of the roles:

Check out this demo link for reference

I made some slight changes to your template to ensure each input is not duplicated. You also don't need to use both :checked and v-model:

<div id="app">
  <div class="checkbox checkbox-success" v-for="role in allRoles">
     <input :id="role.name" type="checkbox" :value="role.id" v-model="userInfo.roles">
     <label :for="role.name">@{{ role.name }}</label>
  </div> 
  {{userInfo.roles}}
</div>

In your Vue script:

new Vue({
  el: "#app",
  data: {
    allRoles: [
      {
        id: 1,
        name: 'test_role'
      },
      {
        id: 2,
        name: 'another_role'
      },
      {
        id: 3,
        name: 'pizza eater'
      },
      {
        id: 4,
        name: 'peanuts eater'
      }
    ],
    userInfo: {
        id: null,
        fullname: '',
        phone: '',
        email: '',
        created_at: '',
        roles: [1, 3], // User's selected roles
        permissions: []
    },
  }
})

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

Transmit information from an HTML input field (not a form) to a Python CGI script through AJAX

I am currently facing a challenge where I need to send data programmatically without using form fields directly to a python CGI script. The issue lies in not knowing how to extract this data in Python. Normally, with a form, I could use "form = cgi.FieldSt ...

What is the best way to reach a link using Selenium?

Challenge : Unable to interact with a link using JavaScript through Selenium. Attempted Solutions: element = driver.find_element_by_css_selector(a {href: "javascript:void(0)"}) resulted in a SyntaxError. element = driver.execute_script("ja ...

Getting a unique identifier from localStorage for a delete button is essential for efficiently removing specific items

Struggling to retrieve an id from localStorage despite multiple attempts. My localStorage data within events looks like the sample below. [{"id":"ef5","title":"wan","start":"2016-05-12","end":"2016-05-13"},{"id":"ef6","title":"wana","start":"2016-05-21"," ...

In a Vue serverless web application, OpenLayers Map object fails to trigger events

In my Vue serverless web application, I have implemented an OpenLayers map initialized in the mounted lifecycle method. The map is populated with ImageWMS layers that are updated by various functions. After updating the parameters of these layers, I call ...

Loading webpage with Ajax and verifying status code

I'm having an issue with a code that is meant to check if a page has loaded and then alert me with a status. However, the code doesn't seem to be working properly. I would really appreciate it if someone could take a look at it and point out wher ...

Is there a way to send a preexisting JSON object to an OPTION in jQuery or JavaScript?

What is the best way to pass a preexisting JSON as a data value in an HTML option tag? I am aware that I can manually pass individual variables like this: <option data-value='{"name":"rajiv","age":"40"}'>a</option> However, if I ha ...

Angucomplete Alternative solves the challenge of accessing remote URLs

I have been using the Angucomplete Alt directive for creating an autocomplete feature. It has been working well so far, but now I want to customize a specific request to be sent to my server. <div angucomplete-alt id="input-name" ...

assigning the browser's width to a variable within an scss file

Is there a way to dynamically set the browser's width as a variable? I am familiar with @media queries, but I need to calculate the browser's width for a specific purpose. I attempted using jQuery to achieve this, and it works well with a fixed ...

Troubleshooting: Bootstrap Modal in .NET MVC not appearing on screen

Below is the code that manages order quotes and includes an if statement. The objective is to display an error message using TempData and Bootstrap Modal if the product quantity in the order exceeds the stock quantity. However, despite TempData not being n ...

Add a checkbox element to a web API using ReactJS

I'm currently learning react and encountering an issue with checkboxes that I can't seem to resolve. I am working on a modal for updating and inserting data in a .net core web api, which is functioning correctly. However, within the app, I'm ...

What methods can be used to effectively scale a single image file for a responsive design?

I am working with an img tag that is placed inside a container with 30 pixels of horizontal padding. The current setup displays a 640-pixel wide image if the screen width is greater than or equal to 670 pixels, and a 320-pixel wide image otherwise: <im ...

What is the best way to dynamically load my React component?

Is there a way to dynamically load my React toolbar component based on state changes? constructor(props) { super(props); this.state = { currentPageNumber: 0, }; } render(){ return( <View> ...

Copying to the clipboard now includes the parent of the targeted element

Edit - More Information: Here is a simplified version of the sandbox: https://codesandbox.io/s/stupefied-leftpad-k6eek Check out the demo here: https://i.sstatic.net/2XHu1.jpg The issue does not seem to occur in Firefox, but it does in Chrome and other ...

JavaScript - Iterating over an object using a loop

I'm attempting to generate dynamic buttons based on an object: var buttonsMenu = { "A":{ A1: 97, A2: 85, A3: 65, A4: 70, A5: 40 }, "B":{ B1: 97, B2: 85, B3: 65, B4: 70, B5: 40 } }; var categoryButt ...

Is the epoch date format not compatible with the ngx bootstrap datepicker?

Consider this scenario: Jun 13, 2003, 23:11:52.454 UTC represented in epoch date format as 1055545912454. However, when I input this value as bsValue, I receive undefined. Objective My goal is to send the date in epoch format when making a server request ...

Retrieve all entries and merge a field with aggregated information in Mongoose (MongoDB)

I am faced with the challenge of working with two Mongo collections, Users and Activities. The Activities collection consists of fields such as createdAt (type Date), hoursWorked (type Number), and a reference to the user through the user field. On the oth ...

combine 2 documents

Two HTML files are on my hands. Both of these HTML files need to be combined. Is there a method in JavaScript or Jquery that can merge two files into one? I have looked at the append and other functions in Jquery, but I am dealing with two large files. ...

What is the process for transforming an AJAX request's onreadystatechange into a promise?

During the process of making a javascript AJAX request, I initially utilized the traditional callback approach to call the callback function within the onreadystatechange and retrieve all the values of readyState. However, upon switching my callback funct ...

What is preventing my content from showing up when clicked like this?

I have created a javascript script to reveal hidden content, but for some reason it is not working when I click on it. Can anyone provide assistance? Below is the script I am using: <script src="style/jquery/jquery.js"></script> <script> ...

Spotting the Visible Element; Detecting the Element in

Currently, my webpage has a fixed header and I am facing the challenge of dynamically changing the styling of the li elements within the navigation based on the user's scrolling position. To achieve this, I believe the most effective approach would b ...