What is the best way to prevent the use of ctrl key in multiple select feature of vue.js

Recently, I decided to create a custom multiselect feature without using any pre-made packages.

However, I found it frustrating that in order to select multiple elements, I had to use the ctrl key.

This functionality was not user-friendly, and I wanted to create a solution using a custom function instead.

Here's a sample code snippet showcasing how I approached this challenge:

<template>
  <select multiple v-model="selected">
      <option v-for="item in items" v-bind:key="item.id">{{item.name}}</option>
  </select>
</template>

<script>
export default {
  name: 'SelectMultiple',
  props: {
    items: Array,
  },
  data(){
    return{
      selected: ['option1']
    }
  },
}
</script>

Answer №1

To improve your selection process, consider using the :value attribute instead of v-model and implement a method for handling the click event:

Vue.component('myselect', {
  template: `
    <div>
      <select multiple :value="selected" @click="selection">
        <option v-for="item in items" :key="item.id" :selected="isSelected(item.name)">{{item.name}}</option>
      </select>
      {{selected}}
    </div>
  `,
  props: {
    items: Array,
  },
  data(){
    return{
      selected: ['option1']
    }
  },
  methods: {
    isSelected(item) {
      return this.selected.includes(item) 
    },
    selection(e) {
      const el = e.target.value;
      if(this.selected.includes(el)){
        this.selected = this.selected.filter(s => s !== el)
      } else {
        this.selected = [...this.selected, el]
      }
    }
  }
})
new Vue({
  el: "#demo",
  data(){
    return{
      items: [{id:1, name:'option1'}, {id:2, name:'option2'}, {id:3, name:'option3'}, {id:4, name:'option4'}, {id:5, name:'option5'}]
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
   <myselect :items="items"></myselect>
</div>

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

Include a Vue component within another Vue component in a Laravel application using VueJs

I've recently integrated Vue.js into my Laravel project and encountered an issue when trying to call a component within another component. After running the command npm run dev, I received a webpack error. Here is the code snippet from my parent comp ...

What is the solution for fixing a "MongoError: E11000 duplicate key error collection" issue in MongoDB?

After setting up a new Mongo collection for a fresh project, I encountered an error when attempting to add a new user. The error message displayed was as follows: MongoError: E11000 duplicate key error collection: GestorMedico.users index: username_1 dup k ...

What's causing my React app's slideshow to malfunction?

Struggling with styling my React app after importing w3.css and attempting to create a slideshow with 3 images in the same directory as the component being rendered. As someone new to React and web development, I'm facing challenges in getting the des ...

Leveraging React Router v5 along with Code Splitting and Server Side Rendering for optimized Data Prefetching

For a current project, I am using react-router v3 specifically for server-side rendering with data prefetching. The most efficient way to achieve this is by maintaining a centralized route configuration in either an object or an array, and iterating throug ...

Having trouble with your Ajax call to an express route?

Trying to initiate an ajax call from a JavaScript file to an express route within a Node.js application, while keeping in mind that the JavaScript file is also part of the same Node.js application. Encountering an issue where the data passed to the route ...

How can I parse a JSON string in a node.js environment?

My current challenge involves sending a JSON string and parsing it on the server-side in node js. The specific value I am trying to extract is the title, but I keep encountering undefined when attempting to parse it. This is my current approach: Home.ejs ...

Issues with navigating jQuery UI links while offline in Google abound

Hello, I am a newcomer to jQuery and I am facing an issue with my code. I added the <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> but for some reason, my jQuery is not working. I have tried searching ...

Guide on creating my inaugural HTML embeddable widget?

A client recently requested me to create a JavaScript (MooTools)/HTML/CSS/PHP based game as a deployable widget. This will be my first time developing a widget, so I am seeking advice and insights to help me navigate any potential challenges from experie ...

Data does not have a permanent home in MongoDB

Recently, I delved into the world of nodejs, mongoose, and express with the intention of creating a basic twitter clone. However, I encountered an issue where nothing happens when I attempt to submit a new tweet. Below is the code snippet I'm working ...

Updating an HTML element by using the input value in a text field with JavaScript/jQuery

Although it may seem straightforward, I am new to Javascript and struggling to find or create the script I need. I have a list of BIN numbers for credit cards and want to extract the first 6 digits of the card number field to determine the type of card, an ...

Developing a dynamic modal using Angular and embedding Google Maps within an iframe

I'm currently working on implementing a modal in my Angular application that, when opened, displays Google Maps within an iframe. The problem I'm facing is that the iframe isn't loading and I'm receiving this error in the browser conso ...

Find the exact length of a string in an HTML5 canvas

In my HTML5 canvas project, I am overlaying text on an image (creating a meme generator). My goal is to determine the perfect font size so that the text covers the entire width of the canvas. Is there a JavaScript solution to calculate the ideal font size ...

Is there a way to both halt the script running for a specific route and return a status 500?

If a custom function encounters an error, I want to halt the script and return a 500 error response. Unfortunately, my script is ignoring the error and proceeding with the execution. ./helpers.js const requiredEnv = (vars, callback) => { const unset ...

Do you need to discontinue a live connection?

Currently, I am in the process of setting up a notification system using StopmJs within React. To gather the count of new messages and the message list, I have subscribed to two destinations. I am curious if there will be any memory leaks if I decide not ...

Why does the ng-click function fail to execute when using the onclick attribute in AngularJS?

Whenever I try to invoke the ng-click function using onClick, I encounter an issue where the ng-click function is not being called. However, in my scenario, the model does open with the onClick function. //Function in Controller $scope.editProductDetail ...

What is the best method for housing API endpoints within a Vue JS application?

Currently, I am utilizing vue-cli for the front-end and lumen for the back-end. I am interested in understanding what the best practice is for storing API root URLs and endpoints in Vue? At this moment, I have a file named constants.js within the src dire ...

There are zero assumptions to be made in Spec - Jasmine analyzing the callback function

I've encountered a challenge with a method that is triggered by a d3 timer. Each time the method runs, it emits an object containing several values. One of these values is meant to increase gradually over time. My goal is to create a test to verify wh ...

Challenges with line height in IE when adjusting font size in textarea

I'm facing an issue with adjusting the font size in a textarea using JavaScript. While it works perfectly in Firefox, there are some problems in IE. Specifically, the line-height does not change accordingly. This results in gaps between lines when the ...

Can you recommend a straightforward method in Vue.js for validating the format of user input?

Here is how I have implemented an email sending feature in Vue.js: <template> <button @click="sendMail(); $emit('close')">Send</button> </template> <script> methods: { sendMail () { axios ...

Displaying properties in Vue using a bound component

Offspring Vue.component('xms',{ template : `<div> {{failureMsg}} </div>`, props : { failureMsg : '', minimumLength : '', } } ) Forefather html <xms errorMsg="Is ...