Activate the Vue checkbox option

Starting out with Vue and web development. I am currently building my app using Laravel and Vue.

This is the code snippet I am working on:

created: function () {
let self = this;
self.setActive('tab1');
axios.get(this.$apiAdress + '/api/tasks/create?token=' + localStorage.getItem("api_token"))
.then(function (response) {
self.documentDircionary = response.data.documentDircionary;
self.selectedDocumentDircionary = response.data.selectedDocumentDircionary;
}).catch(function (error) {
console.log(error);
self.$router.push({path: '/login'});
});
<template v-for="(option) in documentDircionary">
   <div class="form-group form-row" :key="option.name">
      <CCol sm="12">
         <input type="checkbox" name="selectedDocuments[]" :id="option.value" /> {{ option.label }}
      </CCol>
   </div>
</template>

The code displays checkboxes correctly - everything seems to be working fine. My issue lies in setting the selected attribute for the checkboxes.

The array selectedDocumentDircionary received from the API looks like this:

"selectedProducts": [1,2,43]

I'm wondering how I can set the 'checked' state only for the checkboxes that match the values in selectedProducts?

Your assistance would be greatly appreciated.

Answer №1

You can utilize the :checked attribute to indicate that a checkbox should be selected based on the items in your selectedProducts array.

View the live demonstration below:

const app = new Vue({
  el: '#app',
  data() {
    return {
        selectedProducts: [1, 2, 43],
      documentDircionary: [{
        name: 'checkbox1',
        value: 1,
        label: 'Checkbox 1'
      }, {
        name: 'checkbox2',
        value: 2,
        label: 'Checkbox 2'
      }, {
        name: 'checkbox3',
        value: 3,
        label: 'Checkbox 3'
      }, {
        name: 'checkbox4',
        value: 4,
        label: 'Checkbox 4'
      }, {
        name: 'checkbox43',
        value: 43,
        label: 'Checkbox 43'
      }]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js"></script>

<div id="app">
<template v-for="option in documentDircionary">
   <div :key="option.name">
         <input type="checkbox" name="selectedDocuments[]" :id="option.value" :checked="selectedProducts.includes(option.value)" /> {{ option.label }}
   </div>
</template>
</div>

Answer №2

To determine if the current element's id is in an array, you can use :checked:

<template v-for="(option) in documentDircionary">
   <div class="form-group form-row" :key="option.name">
      <CCol sm="12">
         <input type="checkbox" name="selectedDocuments[]" :id="option.value" :checked="selectedProducts.includes(option.value)" /> {{ option.label }}
      </CCol>
   </div>
</template>

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

How to return the same value as the input value in Vue before the action is completed

When creating a component and module for functionality X while using Vuex for state management, the code initially works fine. However, after the first insertion, the Getter function consistently returns the previous input value before the action is commit ...

Challenges with Media Queries post Integration of MUI Library in React

I have been scratching my head for the last few hours. I needed to utilize a react library to design my dog app for a project. Opting for the MUI library, it has been effective for the grid layout. However, the challenge arises when attempting to implement ...

Modify Ripple Color on Material UI < Button /> Click Event

This is my custom button component called <MyButton /> import React from 'react'; import { withStyles } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; const styles = theme => ({ bu ...

`Multiple Autocomplete feature that allows rendering of previously selected items`

I've encountered a slight issue with my autocomplete feature. On the same page, I have two different autocompletes set up. Both of them pull elements via ajax from separate sources and use the _render option to display the items. The problem arises wi ...

Exploring the DOM in JavaScript: Searching for the final ancestor containing a specific attribute

Check out this example of HTML code: <div id="main1" data-attribute="main"> <div id="section2" data-attribute="subsection"> <div id="nested3" data-attribute="sub-subsection"> </div> </div> </div> <div id= ...

Determining the currently active tab in Material UI: A simple guide

I am currently working with the Material UITabs component. I am facing an issue where I need to display details specific to each tab on hover, but my current setup shows the details for all tabs regardless of their active state. Below is how I have impleme ...

Modifying worldwide variables within an ajax request

After spending considerable time attempting to achieve the desired outcome, I am faced with a challenge. My goal is to append the object from the initial ajax call after the second ajax call. However, it appears that the for loop is altering the value to ...

Trouble linking JavaScript and CSS files in an Express App

Could someone assist me in understanding what is causing my code to malfunction? Why is it that my javascript and css files do not execute when the server sends the index.html file to the browser? I have a simple setup with an html page, javascript file, ...

In configuring the print settings, I specified margins to ensure proper formatting. However, I noticed that the margin adjustment only applies to the first page. I need

I have a method that retrieves margin top value from the backend. It works perfectly on the first page of print, but on the second page, the margin top space is missing. initializePrintingSettings() { this.printService.fetchPrintSettings().subscribe(respon ...

Error: The function $compile does not exist

Currently, I am working on developing an AngularJS directive using TypeScript. While testing my code in the browser, I encountered the following error: TypeError: $compile is not a function at compileComponent.js:14 Interestingly, the TypeScript compiler ...

Rule for jQuery validation based on variables

I am facing an issue with validation of login asynchronously in my HTML form using the jQuery Validation Plugin. I would like to trigger a request for login validity on blur, and validate it upon receiving a response. Below is the code snippet: var login ...

The error message "TypeError: default is not a function when using vitest" indicates that

I am currently utilizing vitest for unit testing in my Vue application. After writing some tests, I encountered a failure with the error message: 'TypeError: default is not a function'. However, there's no instance of a function called defau ...

Refreshing the DOM following an API call using VueJS

Struggling with updating the DOM after fetching data from an API. Although my object is successfully fetching the data, the DOM renders before receiving the API Data and fails to update afterward. I'm puzzled as to why it's not refreshing itself ...

Finding the current div based on the scrolling position can be achieved without the use of jQuery

Seeking assistance with a coding challenge. I have a solution in jQuery, but we require the solution in plain JavaScript or Angular. It seems like something is missing. Take a look at this fiddle. The objective is to highlight the corresponding left panel ...

A ReactJS Error occurred: {error: 400, reason: "Failed match", message: "Failed match [400]", errorType: "Meteor.Error"}

I encountered an issue while attempting to send form data to the server when clicking on the Next Button in a Wizard Form. The error that occurs is related to an "Undefined User" warning displayed in the Console during Step 1 of the form submission: " { ...

Preserve the data integrity through two consecutive jsp pages

My task involves extracting a value from a table: <script type="text/javascript"> var activeRequest; $(document).ready(function(){ $(".i_search").on("click", function(event){ event.preventDefault(); acti ...

I am struggling to capture the user's input and display it on a webpage using HTML and JavaScript. Can you help me identify where I may be going wrong in this process?

Good day! I am fairly new to the programming world and have recently embarked on my first JavaScript project. I've chosen to create a simple budgeting app. However, I'm struggling with displaying user input on the page. Something seems off with ...

What could be causing the issue with my hour parameter in node-cron?

Having difficulty setting up a cron job to run with node-cron every Monday at 8:30. I've tried using "30 8 * * Mon" and even "30 08 * * Mon", but it doesn't seem to work. Interestingly, "30 * * * Mon" does work and runs every hour on the 30th min ...

What are the steps for setting up jScroll?

As a newcomer to JS & jQuery, I appreciate your patience. I've been working on creating a dynamic <ul> list using JS, and I'm happy that it's finally coming together. Now, my next step is to incorporate infinite scrolling into my ...

Refreshing a webpage following an AJAX call

Whenever I make a post request to an API, I receive a response. However, even though the data is saved when I hit the API, I have to manually refresh my blade.php page to see the newly added data. Is there a way to automatically update my blade with the ...