Enhancing your JQuery Select2 plugin by incorporating a Checkbox feature

I am currently utilizing the jQuery select2 plugin to enable multiple selections. My goal is to incorporate a checkbox for each selectable option.

Depending on whether the checkbox is checked or unchecked, the dropdown option should be selected accordingly.

Sample HTML:

<select multiple="multiple" id="e1" style="width:300px">
    <option value="AL" selected> Alabama</option>
    <option value="Am">Amalapuram</option>
    <option value="An">Anakapalli</option>
    <option value="Ak">Akkayapalem</option>
    <option value="WY">Wyoming</option>
</select>

JS:

$("#e1").select2();

View Demo

Answer №1

Check out this working fiddle!

Instead of using a checkbox, you can toggle classes. See the example below.

HTML :

<select multiple="multiple" id="e1" style="width:300px">
    <option value="AL" selected> Alabama</option>
    <option value="Am" selected>Amalapuram</option>
    <option value="An" selected>Anakapalli</option>
    <option value="Ak" selected>Akkayapalem</option>
    <option value="WY" selected>Wyoming</option>
</select>

<button type='button' id='submit'>Submit</button>

JS :

$("#e1").select2();

$('body').on('click','.select2-search-choice', function(){
  $(this).toggleClass('selected')
})

$('body').on('click','#submit', function(){
  $('#s2id_e1 .select2-search-choice.selected').each(function(){
    console.log($(this).text());
  })
})

CSS :

.select2-container-multi .select2-choices .select2-search-choice.selected{
    background-color: #286090;
    border-color: #204d74;
    color: #FFF;
    background-image : none;
}

I hope this solution is useful to you.

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 implement functional component in ReactJs

I am currently working with Reactjs and utilizing the Nextjs framework. In my project, I am attempting to retrieve data from a database using Nextjs. However, I am encountering an error that states "TypeError: Cannot read property 'id' of undefin ...

CSS - When using both display: flex and position: absolute, the anchor point is shifted

I have a flexbox element with three children. I want the second child to overlap the first child using absolute positioning, like this: Desired Outcome: https://i.stack.imgur.com/i479w.png It's important that the second child appears on top of the ...

Avoid unnecessary re-renders in React Redux by ensuring that components do not update when properties are not utilized in their

I'm encountering an issue with a component that keeps re-rendering. I've implemented Redux to handle my states. Within a component, I access a property (isPlaying: bool) from the state using mapStateToProps in various methods of the component, ex ...

Is there a way to reach a different function within the value of the react Context.Provider?

Right now, I am learning how to utilize the react context API. Within my react Provider class, I have some state data and functions stored in the value={}. But I am curious, how can I call a function inside this value from another function within the same ...

Add a CSS and jQuery hover effect to display text over an image, requiring users to click twice on their mobile device

I have a bunch of panels for different categories that change the background image when hovered over, display some introductory text, and lead to a URL when clicked. However, on mobile devices, you need to tap the panel twice to activate the URL. What I&a ...

Transmit parameters via onclick event on FullCalendar

I have been utilizing the full calendar feature and it's been functioning properly. However, I am encountering an issue with sending parameters via onclick event. Below is the JavaScript code that I currently have: <script> $(document).ready(fu ...

Passing the results of sequelize through express after the completion of a forEach iteration

In an express route, I am running a somewhat complex sequelize query that requires me to run a second query afterward to append necessary data to the result: //Get inboxes based on passed params router.get('/:data', function(req, res, next) { ...

Typescript Tooltip for eCharts

I'm working on customizing the tooltip in eChart v5.0.2 using Typescript, but I'm encountering an error related to the formatter that I can't seem to resolve. The error message regarding the function keyword is as follows: Type '(param ...

Displaying data on View is not working after navigation

I'm facing an issue where the data is not displaying on the view after routing, even though it appears in the console. Surprisingly, if I don't change the view, the data shows up. Additionally, if I call the service directly from the view, I can ...

CSS animations are only functional when the Developer Tools are activated

I recently implemented a transition to uppercase in CSS, but it seems to only work when I open dev tools in Mozilla and not at all in Chrome. This is my first attempt at using animations in CSS, so any feedback on my code is appreciated. I'm curious ...

The term "this" in the global scope versus within a function in the Node.js environment

console.log(this) // {} function abc(){ console.log(this) } abc() // global The concept of this can vary between the global space and inside a function in Node.js. console.log(this === module.exports) // true function abc(){ ...

I am facing difficulties in installing the necessary node modules for my Angular project

After attempting to run npm install, an error message is displayed towards the end: error syscall unlink 22396 error The operation was rejected by your operating system. 22396 error It's possible that the file was already in use (by a text editor or ...

How to place a div with 100% width at the bottom of a float with a fixed width

Each day the same question seems to pop up, yet this particular issue has me stumped... My goal is a simple one - I aim to design a fixed width layout with 3 columns, while ensuring that the header and footer stretch across 100% of the screen. Everything ...

Troubleshooting: ReactJS CSS Class Issue

I'm fairly new to working with ReactJS and I've encountered an issue while trying to create a class for a specific form. Below is the code I've written: import React, { Component, PropTypes } from 'react'; import s from './s ...

When entering a sub-URL into the browser address bar, the routes do not display as expected

I am encountering an issue with navigating to different routes within my React application. While the home route is visible and functions properly when I start the app locally (npm run dev), I am unable to access other routes. No errors are displayed in t ...

Leveraging Node.js socket.io alongside React's web worker for streamlined communication

I have a project that involves using socket.io, React.js, and Webworkers https://i.sstatic.net/3SUg3.png Components A and B are child components of the Home page component. These components also function as tabs, so when A is mounted, B is unmounted, and ...

Leverage the NextRouter functionality without the need for a React component

I've created a custom hook that checks if a user is logged in and redirects them to the login page if not. Below is a simplified version of the hook assuming the user is not logged in: import { useRouter } from 'next/router'; export default ...

Designing a rounded border radius for various child elements within a layout

I am currently working on creating a circular container that houses an image and a description overlaid at 50% opacity. Here is what I have achieved so far: https://i.stack.imgur.com/pIkO1.png My goal is to apply a uniform border-radius to the entire div ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...

Tips for resetting the mapbox geocoder

Using the Mapbox Geocoder along with multiple select menus to customize a map has been my latest project. I am currently working on resetting the geocoder once a user selects an option from the menu, clearing the input field and removing the marker in the ...