Guide to setting a checkbox as selected using the v-model value for vue-multiselect

Issue: The selected option checkbox is not getting selected, regardless of the checked state being true or false.

Important Note: I always want the value model without the inclusion of the checked state in it.

Refer to the image below for a visual representation of my problem (please see yellow area)

https://i.sstatic.net/CfNZy.png

This is what I have attempted so far:

new Vue({
    components: {
    Multiselect: window.VueMultiselect.default
    },
    data: {
    value: [],
    options: [
        {   language: 'JavaScript', library: 'Vue.js', checked: false },
      { language: 'JavaScript', library: 'Vue-Multiselect', checked: false },
      { language: 'JavaScript', library: 'Vuelidate', checked: false }
    ]
    },
  methods: {
    customLabel (option) {
      return `${option.library} - ${option.language}`
    },
    onSelect (option) {
        console.log("Added");
      let index = this.options.findIndex(item => item.library==option.library);
      this.options[index].checked = true;
      console.log(option.library + "  Clicked!! " + option.checked);
    },
    
    onRemove (option) {
        console.log("Removed");
      let index = this.options.findIndex(item => item.library==option.library);
      this.options[index].checked = false;
      console.log(option.library + "  Removed!! " + option.checked);
    }
  },
  created(){
       this.value = [{  language: 'JavaScript', library: 'Vue.js',checked:true }];
  }
}).$mount('#app')
* {
  font-family: 'Lato', 'Avenir', sans-serif;
}

.checkbox-label {
  display: block;
}

.test {
  position: absolute;
  right: 1vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb9d9e8ec6869e879f82988e878e889fabd9c5dbc5d9">[email protected]</a>/dist/vue-multiselect.min.css" rel="stylesheet"/>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="502625357d3d253c243923353c35332410627e607e63">[email protected]</a>/dist/vue-multiselect.min.js"></script>
<div id="app">
  <multiselect 
select-Label=""
selected-Label=""
deselect-Label=""
v-model="value" 
:options="options"
:multiple="true"
track-by="library"
:custom-label="customLabel"
:close-on-select="false"
@select=onSelect($event)
@remove=onRemove($event)
>
<span class="checkbox-label" slot="option" slot-scope="scope" @click.self="select(scope.option)">
{{ scope.option.library }}
<input class="test" type="checkbox" v-model="scope.option.checked" @focus.prevent/>

</span>
</multiselect>
<pre>{{ value }}</pre>
</div>

If you can provide assistance, I would greatly appreciate it. Thank you in advance!

Answer №1

It seems like you are looking to display checkboxes without using the checked field in the v-model. This extra field was only added to facilitate the rendering process.

  1. If you wish to render checkboxes,
  2. and do not require the checked property in the v-model,

You can simplify your code by eliminating the checked property entirely. Instead, you can easily determine the value by comparing it directly to the v-model. This will result in a cleaner and more concise implementation.

Check out the modified example below:

new Vue({
  components: {
    Multiselect: window.VueMultiselect.default
  },
  data: {
    value: [],
    options: [{
        language: 'JavaScript',
        library: 'Vue.js'
      },
      {
        language: 'JavaScript',
        library: 'Vue-Multiselect'
      },
      {
        language: 'JavaScript',
        library: 'Vuelidate'
      }
    ]
  },
  methods: {
    customLabel(option) {
      return `${option.library} - ${option.language}`
    },
    isSelected(option) {
      return this.value.some((op) => op.library === option.library)
    }
  },
  created() {
    this.value.push(this.options[0])
  }
}).$mount('#app')
* {
  font-family: 'Lato', 'Avenir', sans-serif;
}

.checkbox-label {
  display: block;
}

.test {
  position: absolute;
  right: 1vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e2949787cf8f978e968b91878e878196a2d0ccd2ccd0">[email protected]</a>/dist/vue-multiselect.min.css" rel="stylesheet" />
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e787b6b23637b627a677d6b626b6d7a4e3c203e203d">[email protected]</a>/dist/vue-multiselect.min.js"></script>
<div id="app">
  <multiselect select-Label="" selected-Label="" deselect-Label="" v-model="value" :options="options" :multiple="true" track-by="library" :custom-label="customLabel" :close-on-select="false">
    <span class="checkbox-label" slot="option" slot-scope="scope">
    {{ scope.option.library }}
      <input class="test" type="checkbox" :checked="isSelected(scope.option)" @focus.prevent :key="scope.option.library" />
    </span>
  </multiselect>
  <pre>{{ value }}</pre>
</div>

Answer №2

Do not bother assigning the value as it loses its reactivity in that context. Just pick the correct option and mark it as checked. As seen in the code snippet below, I've made changes to the created block.

new Vue({
  components: {
    Multiselect: window.VueMultiselect.default
  },
  data: {
    value: [],
    options: [{
        language: 'JavaScript',
        library: 'Vue.js',
        checked: false
      },
      {
        language: 'JavaScript',
        library: 'Vue-Multiselect',
        checked: false
      },
      {
        language: 'JavaScript',
        library: 'Vuelidate',
        checked: false
      }
    ]
  },
  methods: {
    customLabel(option) {
      return `${option.library} - ${option.language}`
    },
    onSelect(option) {
      console.log("Added");
      let index = this.options.findIndex(item => item.library == option.library);
      this.options[index].checked = true;
      console.log(option.library + "  Clicked!! " + option.checked);
    },

    onRemove(option) {
      console.log("Removed");
      let index = this.options.findIndex(item => item.library == option.library);
      this.options[index].checked = false;
      console.log(option.library + "  Removed!! " + option.checked);
    }
  },
  created() {
    // Don't need these lines triggering reactivity issues
    // this.value = this.options[0];
    // this.value.checked = true;

    // Instead, consider the following approach
    this.value.push(this.options[0]);
    this.value.push(this.options[1]);

    for (let i = 0; i < this.value.length; i++) {
      this.value[i].checked = true;
    }

  }
}).$mount('#app')
* {
  font-family: 'Lato', 'Avenir', sans-serif;
}

.checkbox-label {
  display: block;
}

.test {
  position: absolute;
  right: 1vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2c2f3f77372f362e33293f363f392e1a68746a7468">[email protected]</a>/dist/vue-multiselect.min.css" rel="stylesheet" />
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e282b3b73332b322a372d3b323b3d2a1e6c706e706d">[email protected]</a>/dist/vue-multiselect.min.js"></script>
<div id="app">
  <multiselect select-Label="" selected-Label="" deselect-Label="" v-model="value" :options="options" :multiple="true" track-by="library" :custom-label="customLabel" :close-on-select="false" @select=onSelect($event) @remove=onRemove($event)>
    <span class="checkbox-label" slot="option" slot-scope="scope" @click.self="select(scope.option)">
    {{ scope.option.library }}
      <input class="test" type="checkbox" v-model="scope.option.checked" @focus.prevent/>
      
    </span>
  </multiselect>
  <pre>{{ value }}</pre>
</div>

Answer №3

The plugin functions more like an array of selectable options rather than checkboxes. To have certain options already selected, you must include them in your v-model array ("value" in this case).

The data for options.checked is unnecessary in this scenario and serves no purpose.

Here is an example based on your code: Your data() function should look like this:

options: [
        {   language: 'JavaScript', library: 'Vue.js'},
      { language: 'JavaScript', library: 'Vue-Multiselect'},
      { language: 'JavaScript', library: 'Vuelidate' }
    ],
value: [
        {   language: 'JavaScript', library: 'Vue.js'},
      { language: 'JavaScript', library: 'Vue-Multiselect'},
      { language: 'JavaScript', library: 'Vuelidate' }
    ]

If you use these data structures in your app, all the options will be preselected.

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

Ways to make a button blink using AngularJS

Currently working on an AngularJS SPA application where a button is present in the front-end HTML page. When this button is clicked, it triggers an operation which takes some time to complete. I want to inform the user that the operation is still in prog ...

The revised document now exceeds 16,777,216 in size

When attempting to add new data to an array using mongoose, I encountered two errors. Here is the code snippet in question: return await db.fileMeta.findOneAndUpdate({ username: username, 'files.fileUID': { $ne: data.fileUID } ...

Navbar collapse not functioning properly on HTML, CSS, and JavaScript

I have developed a CSS code snippet: .nav{ right: 0px; left: 0px; margin-top: 0px; margin-bottom:20px; height: 35px; text-align: center; background-color: red; z-index: 1; } .sticky { background: #000; text-align: center; ...

Difficulty with Mongoose persisting data on api/mlab

I've developed a search API that utilizes the Imgur API to fetch JSON data of images based on user queries. Additionally, it keeps track of users' latest searches in the "/latest" URL. However, I'm encountering an issue where the array retur ...

What is the best way to retrieve data once an action has been completed in Redux?

After triggering specific actions to update an array of objects in my global state, I want to send a PUT request to my Firebase database. This action can involve adding, deleting, or editing objects within the array, and I need to initiate the request righ ...

Encountering difficulty in retrieving data from an unidentified JSON array using Javascript

Exploring the realm of Javascript and JSON, I find myself faced with a challenge - accessing values in an unnamed JSON array. Unfortunately, as this is not my JSON file, renaming the array is out of the question. Here's a snippet of the JSON Code: [ ...

Having trouble incorporating choreographer-js, an external JavaScript library, into my Nuxt project as it is not functioning correctly

Just starting out with vue.js and nuxt.js, I wanted to experiment with integrating an external JavaScript library into my nuxt.js project. My goal is to test out the functionality provided by this library: The library in question can be found here: https: ...

Tips for accessing payment details from a stripe paymentElement component in a React application

Here is a basic code snippet for setting up recurring payments in Stripe: await stripe ?.confirmSetup({ elements, confirmParams: { return_url: url, }, }) After browsing through the documentation and the internet, I have two unanswere ...

The custom shader on the object appears distorted when the object is in motion

Link to CodePen I am currently working on a basic diffuse lighting shader, and I have encountered an issue where the shading does not update correctly when I apply position or rotation changes to the object. Moving the "Custom Point Light" position seems ...

Trigger Screen Reader to Announce When a Component Is Deleted

When the last filter item is removed, I want the screen reader to announce "All Filters Are Removed." However, if the active filter component is removed without any other element to assign an aria-label attribute, I'm not sure how to handle this situa ...

Receiving JSON dynamically (using socket.io) may result in parsing issues

I am currently working with JSON data that is correctly formatted at 100% accuracy. My issue arises when I execute the following code successfully: var data = {"datas":[{"matts":{"active":"1","status":"off"},"config":null,"adapters":[]}}]}; console.dir( ...

problem of keeping behat/selenium browser open after execution

I am attempting to execute the behat/selenium test with Chrome browser by running the following feature scenario. I would like to keep the browser window open instead of closing the Chrome immediately. Even though I have implemented the iWaitForSeconds ste ...

Changing the prototype of a generator function

TL;DR I am looking to enhance a generator function instance by adjusting its prototype, specifically the object received when calling a function*. Imagine I have a generator function: function* thing(n){ while(--n>=0) yield n; } Next, I create a ...

Trap mistakes while utilizing async/await

Within my Express application, I have a register function for creating new users. This function involves creating the user in Auth0, sending an email, and responding to the client. I am looking to handle errors from Auth0 or Postmark individually and send ...

Ordering two arrays in a for loop

I have two arrays to manage, one for numbers and the other for names. const number = ['91xxxx','1xxxx','92xxxx'] const name = ['Abhi','Arun','Aaron'] The goal is to pair each number with a corres ...

Get the Zip file content using PushStreamContent JavaScript

I am looking for the correct method to download a PushStreamContent within a Post request. I have already set up the backend request like this: private static HttpClient Client { get; } = new HttpClient(); public HttpResponseMessage Get() { var filenames ...

Storing an array in $cacheFactory with AngularJS

Having some trouble saving an array in AngularJS' $cacheFactory. When attempting to retrieve the array, it's coming back as undefined. Here is the code snippet: angular.module('cacheExampleApp', []). controller('CacheContro ...

Tips for passing a "NULL" value into a nullable field when making a call from JavaScript to an ASP.NET WebService

Is there a way to pass the value of "NULL" into a nullable field when calling an ASP.NET WebService from JavaScript? I am currently calling the method in this manner from JavaScript: ws_data.SaveTasks(eval({"MyValue":"null"}), OnSaveComplete, OnError, On ...

Stopping the iteration through each AJAX call loop after processing the data

I can't seem to keep track of my SO accounts! The issue at hand: My tool allows users to click on each year for the past decade to display a set of data. Some years may not have any data, but users can still browse through them and possibly receive ...

Is there a better method to determine the width when utilizing the jQuery UI resizable feature for improved efficiency?

I'm currently working on a website that features a resizable sidebar. I want the icons and text within the sidebar to shrink proportionally when the user resizes it. Right now, I have implemented an if statement to check if the sidebar's width fa ...