Vue Js: Creating an array of checkboxes

I have a collection of checkboxes sourced from the main system object where I store all system settings (referred to as getSystem{}).

Within this form, I am retrieving information about a User, who possesses an array of roles []. How can I cross-reference this array of roles with the getSystem.user_roles?

I am familiar with accomplishing this in plain JavaScript. However, how should I approach checkbox input in terms of Vue.js?


    <b-form-group>
      <label for="company">Email Address</label>
      <b-form-input type="text" id="email" v-model="user.email" placeholder="Enter a valid e-mail"></b-form-input>
    </b-form-group>
    // Here I can access user.roles to retrieve the array of roles.
    // How do I iterate through the roles and mark the checkbox if it exists within the user roles??
    <b-form-group v-for="resource, key in getSystem.user_roles" v-if="getSystem.user_roles">
       <label>{{resource.role_name}}</label>
       <input type="checkbox" [what should be placed here to compare with user.roles and mark the checkbox if present??]  > 
    </b-form-group>

Answer №1

The behavior described can be found in detail on the Checkbox binding documentation.

Below is a simple example that follows a similar logic:

new Vue({
  el: '#app',
  data: {
    user: {
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f286978186b286978186dc919d9f">[email protected]</a>',
      roles: [{id: 1, name: 'Client'}]
    },
    roles: [
      {
        id: 1,
        name: 'Client',
      },
      {
        id: 2,
        name: 'Admin',
      },
      {
        id: 3,
        name: 'Guest',
      }
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

<div id="app">
  <div>
    <label>Email</label>
    <input type="text" v-model="user.email" />
  </div>
  <div v-for="role in roles" :key="role.id">
    <label>{{role.name}}</label>
    <input type="checkbox" v-model="user.roles" :value="role"/>
  </div>
  
  <p>User's selected roels</p>
  {{user.roles}}
</div>

Answer №2

<input type="checkbox" v-model="userRoles" :true-value="[]" :value="resource.role_name">

Make sure to include the line :true-value="[]".

Answer №3

Utilizing dynamic checkbox input rendering allows for selecting values based on conditions set within a customized function (in this case, selectUsers). This function is where we can establish the specific conditions that must be met before a value is added to the selected array.

See it in action:

https://i.stack.imgur.com/bQ4bT.gif

This is an example of a complete NuxtJs (Vue) component with placeholder data.

<template>
  <v-container fluid>
    <p>{{selected }}</p>
    <div v-for="user in user_roles" :key="user[0]">
    <input type="checkbox"
      @click="()=>{selectUsers(user[0])}"
      :value="user[0]"
    >
    {{user[1]}}
    </div>
  </v-container>
</template>

<script>
import VueLodash from 'vue-lodash'
import lodash from 'lodash'
export default {
    
    data() {
    return {
      user_roles:[[1,"dd"],[2,"ddd"],[3,"kksse"],[4,"kske"]] ,
      selected:[],
    };
  },
  methods: {
      selectUsers(id){
          //Additional conditions can be checked here before adding to the array.
          if(this.selected.includes(id)){
              this.selected=_.without(this.selected,id)
          }else{
              this.selected.push(id)
          }
      }
  }
}
</script>

Answer №4

<b-form-group v-for="resource, key in getSystem.user_roles" v-if="getSystem.user_roles" :key="key">
   <label>{{resource.role_name}}</label>
   <input type="checkbox" v-model="userRoles" :value="resource.role_name"  > 
</b-form-group>

<script>
  data(){
    return {
      userRoles: []
    }
  }
</script>

Answer №5

When I was server rendering the checkboxes in my situation, what ended up working for me was changing :value to just value

@foreach($carOptions as $option)
<div class="form-check">
    <input class="mx-2 form-check-input cursor-pointer"
           type="checkbox"
           value="{{$option}}" <------ HERE in order for vue to work I had to change from :value to value
           v-model="offer.carOptions">
    <label class="custom-control-label cursor-pointer"
           for="leading">{{ __($option) }}</label>
</div>
@endforeach

Please take note that this code snippet corresponds to a Laravel Blade Templates.

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

Check for a rapid return if the function ends up returning null in JavaScript

Is there a way to make this code more concise? const result = getResult(); if (!result) { return; } // Work with result I have several instances of this code in my project and I'm looking for a simpler solution like: const result = getResult() ...

Transfer the cropped image to the database through AJAX on the client side and PHP on the server side

I am attempting to upload an image to a Database using JavaScript on the client-side and PHP on the server-side. The first step is selecting an image from the gallery. After zooming and cropping the image, it should be passed to the database. The issue ...

Accessing data from a live database in a randomized sequence

When retrieving items from a database, there is often a common code pattern that looks like this: const [dataRcdArray, setDataRcdArray] = useState<never[]>([]); ..... snapshot.forEach((child:IteratedDataSnapshot) => { setDataRcdArray(arr ...

Guide to utilizing the Array find method to retrieve an object in JavaScript

I'm currently working on a Homework assignment that involves passing a parameter called userID to an arrow function. Within this function, the task is to use the .find method on an array named users. This find function should retrieve an object contai ...

The ASP.NET MVC controller did not receive the JSON object properly due to some missing properties

I am facing an issue when trying to pass a JSON object to my ASP.NET MVC controller. The JSON is set in JavaScript in this way: jsonChildren = '{ "childImproItems" : [{ "Theme":"tralalali" }, { "Theme":"tralalali" }]}'; ... $.ajax({ ...

I encountered an issue while attempting to connect to my MySQL database using my Express API endpoint: error message "connect ECONNREFUSED 127.0

I am currently in the process of developing a web application for a bootcamp using Express and MySQL. I have set up a route to handle a GET request to an endpoint which is supposed to query my MySQL database table and retrieve all records. My intention is ...

Analyzing past UTC date times results in a peculiar shift in time zones

When I receive various times in UTC from a REST application, I encounter different results. Examples include 2999-01-30T23:00:00.000Z and 1699-12-30T23:00:00.000Z. To display these times on the front end, I use new Date(date) in JavaScript to convert the ...

Leverage Summernote in conjunction with Vue components to dynamically switch their locations

I am experiencing a strange behavior with Vue components created using v-for. Each component has a textarea for summernote, and initially everything works correctly. The editor loads the text and updates it when edited. However, when the position propert ...

I used npm to install a package, but for some reason, it's not appearing in

When attempting to install jquery using npm, I entered the following command: npm install jquery However, upon opening the destination folder, it was empty. (The below text was copied from cmd) > C:\Users\mandar\Desktop\Mady> ...

How can we refresh the model in Angular.js from a section of the application that has not been 'angularized' yet?

UPDATE: Found a similar question at Call Angular JS from legacy code Working on adding a new feature to an existing application using Angular. Unable to do a complete rewrite, so the challenge is integrating Angular models with the rest of the app that di ...

What could be causing the responsive line chart from nivo to not appear in jsdom while using Jest?

I am currently working on writing UI tests for my application using Jest/Testing Library. In the testing process, I have integrated the ResponsiveLine component from the @nivo/line library. However, I am facing an issue where the Responsive Line componen ...

Rotating images with React

I am encountering an issue with implementing an image carousel in React. Previously, it worked perfectly when I was not using React, but now that I am migrating the page, I am facing an error. ** The carousel is located on the home page: ** const Home = ( ...

What is the best way to show an image on the screen once a submit button is clicked?

I have a hidden loader-bar gif that I want to display when the user submits a form. Here is the code: <p class="loadingImg" style="display:none;"><img src="/design/styles/_shared/classic-loader.gif" alt="" /></p> Is there a way to ...

React Component: Issue with conditional "if else" statement not refreshing in return statement

Starting out in React and the front-end field with minimal experience. Currently attempting to dynamically change the color of the "fill" property in a polygon element using React. If the percentage is greater than 50, I want the color to be green; otherw ...

Integrate an interactive feature to highlight a column in a table, similar to the active class in Netflix

Can anyone assist me in choosing a table header and selecting a column based on classes, similar to Netflix? I am new to VueJS and could use some guidance. Here is an example GIF This is the code I have so far <table class="table"> < ...

Reliable Dropdown Navigation Bars

Once I have successfully implemented three dynamic drop down menus using the combination of jQuery, AJAX, and PHP, the next challenge arises. After populating the dropdown menus based on user selections (e.g., selecting a value in the first dropdown menu ...

Functionalities of HTML controls

I currently have a select element in my HTML code which looks like this: <select> <option id="US" value="US"> </option> <option id="Canada" value="Canada"> </option> </select> My requirements are twofold: ...

Leveraging Jquery and an API - restricted

I have the opportunity to utilize a search API that operates on JSON format through a URL GET. This particular API has a reputation for imposing quick bans, with an appeal process that can be lengthy. If I were to integrate this API into my website using ...

The picture is displayed just once, despite the fact that it was supposed to be returned 50 times within the loop

I'm encountering an issue while trying to use a for loop to render an image in a React component. The loop is not functioning as expected, resulting in the image being displayed only once on the screen even though the intention is to show the same ima ...

Exploring the use of data attributes in jQuery to access JSON objects

I have set a data-attribute for multiple elements and I am looking to access the JSON object using this data attribute in jQuery. <div class="content"> <div class="plans" data-plan="state-1"><span class="pricing-symbol">$</span> ...