Conceal Choices During Search using jQuery Select2

I'm having trouble figuring out how to make the Select2 plugin work for my specific color selection feature.

My goal is to allow users to choose 5 colors from a list, including an "Other" option. When the user selects "Other", they should be able to pick a custom color using a color picker. To achieve this, I created 5 options all named "Other" so that users can select it multiple times if needed. However, I am facing issues with hiding the "Other" options that are not the first one displayed when users search for a color.

I've tried using the following code snippet to show/hide the "Other" options:

$('.multi-select').select2('misc options').on("select2:open", function () {
    $('.select2-results__option[aria-selected="false"]:contains("Other"):not(:eq(0))').hide();
    $('.select2-results__option[aria-selected="false"]:contains("Other"):eq(0)').show();
});

However, binding the same function to the search input element causes erratic flashing of elements and the top "Other" option floating above the select object. This flashing occurs due to conflicting event bindings within the plugin.

I have attempted various solutions such as modifying CSS selectors and applying classes to the <li></li> elements created by Select2, but none have been successful.

Answer №1

If you want to achieve your desired result without modifying the "Other" option, a combination of the select2:select event and the maximumSelectionLength options would be more suitable.

To start, include a default list of colors in your markup along with an "Other" option:

<select multiple="multiple">
  <option value="red">Red</option>
  <option value="blue">Blue</option>
  <option value="green">Green</option>
  <option value="yellow">Yellow</option>
  <option value="custom">Other</option>
</select>

The value for the "Other" option can be set as custom, serving as the flag option to trigger the display of the color picker when selected.

To limit selections to five colors using Select2, initialize it with the maximumSelectionLength option set to 5. Refer to the documentation for an example.

var $element = $("select").select2({
  maximumSelectionSize: 5
});

Next, implement the color picker functionality by detecting the selection of the "Other" option through the select2:select event.

$element.on("select2:select", function (evt) {
  // handle the "Other" option
});

Specifically check for the selection of the "Other" option based on the data passed in and unselect it immediately to allow picking additional custom colors.

function (evt) {
  if (evt.params.data.id === 'custom') {
    evt.params.data.element.selected = false;
    $(this).trigger('change');
  }
}

Proceed with selecting a color, either by using a synchronous prompt or any asynchronous color picker method. Create a custom <option selected> for the chosen color to update the selection.

var color = prompt("Pick a color, any color");
var option = new Option(color, color, null, true);
$(option).insertBefore(evt.params.data.element);
$element.trigger('change');

Now, Select2 will display the newly selected custom color alongside other choices, allowing users to pick multiple custom colors by selecting the "Other" option multiple times.

Combining these steps provides you with the complete solution. You can test the code live on this jsbin link: http://jsbin.com/beluximesi/1/edit?html,js,output

Answer №2

The solution dawned on me. By utilizing the field values as unique identifiers in the backend, I cleverly appended "-other-color" to create a specific CSS selector and eliminate the annoying flickering issue.

.select2-results__options li[id*="-other-color"][aria-selected="false"] ~ li[id*="-other-color"][aria-selected="false"]{
    display:none!important;
}

Considering the list contains more than just color options, employing the tilde selector was essential for targeting elements following the specified attributes.

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

Issue with jquery-scrollify causing overflow content to display incorrectly. Overlapping content and inconsistent behavior across varying page widths

I'm in the process of creating my own personal website and want to incorporate the jQuery-scrollify tool to navigate through different sections. However, no matter what settings I try, I can't seem to get the scrolling behavior consistent across ...

The material icons CDN does not seem to be functioning properly in Next.js

After adding a CDN to the head section of my Next.js project, I encountered an issue where it was not working as expected. import Head from "next/head"; <Head> <link href="https://fonts.googleapis.com/icon?family=Material+Ico ...

I am attempting to dynamically align the images of two articles. The exact heights of the containers are not specified. Can anyone provide guidance on how to achieve this?

My code snippets: <article class="featured"> <img src="http://www.placehold.it/300x100/ff0000"> <p> <!--Text--> </p> </article> <article class="sub-featured"> <img src="http://www.placeh ...

Setting the second tab as the primary active tab

I am currently working on a script that is well-known, and everything is functioning perfectly. However, I want to change it so that when the page is first opened, it displays the second tab instead of the first one (the first tab being a mail compose tab ...

Determine the height using jQuery before adding the class

I've been grappling with jQuery to accurately calculate the height of an element and then apply a specific CSS class to adjust its height. The issue I'm facing is that jQuery seems to be executing these calculations out of order, which is causing ...

Show the textbox automatically when the checkbox is selected, otherwise keep the textbox hidden

Is it possible to display a textbox in javascript when a checkbox is already checked onLoad? And then hide the textbox if the checkbox is not checked onLoad? ...

Guide to utilizing vh units in place of pixels for .scrolltop functionalities

I am trying to change the class of a menu bar after a user scrolls to the next div, which is 100vh tall. The current function works only with screens of my size, being too early or too late on smaller or larger screens. How can I adjust this function to u ...

I'm having trouble getting things to line up properly in Bootstrap5. Can anyone help me figure out why?

When observing this layout, there seems to be a vertical misalignment. The button slightly overflows, while the input field does not. https://i.sstatic.net/pEw2U.png What could be causing this issue? I am currently utilizing Bootstrap 5.2.3 and have incl ...

Issue retrieving Select2 tag values from view to controller in ASP.NET MVC 5

I need assistance in transferring tag values from the view to the controller. Here is my approach: I have a model attribute for fetching Select2 values: In the model: public string[] TagList { get; set; } In the view, I have a select element like this: ...

IE/Firefox returning empty value for Ajax requests

After spending two days trying to solve the issue, I still can't figure out why this code is failing in IE (v11) and Firefox while working fine in Chrome. I have read many questions on similar topics involving caching problems with multiple Ajax call ...

Issue with jQuery connected sortable: clicking to move items is not functioning properly

I am currently working on a project that involves two connected sortable lists using jQuery UI. I have successfully implemented the functionality where clicking on an element in one list will add it to the other list and vice-versa. However, I have encount ...

Fire an event in JavaScript from a different script file

I have created a JavaScript file to handle my popups. Whenever a popup is opened or closed, I trigger a custom event like this: Script File #1 $(document).trigger('popupOpened', {popup: $(popupId)}); If I want to perform an action when the tri ...

Node.js's HTML parsing capabilities on the server side

Is there a way to access and manipulate the content of a div element in an HTML file using Node.js on the server without relying on a web browser? I am also interested in being able to perform jQuery operations like content.find("div.t"). Does anyone know ...

The ellipsis text-overflow feature occasionally malfunctions during a single session when using IE 11

.show-ellipsis { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } <div class="container"> <div class="row show-ellipsis"> {{record.bodyName}} </div> </div> My web application supports versions o ...

Create a one-of-a-kind SVG design with a customized blur effect in

Recently, I've been experimenting with SVG effects and animations and stumbled upon a fantastic example of how to apply a blur effect to an SVG path. However, I'm struggling to figure out how to set a different color instead of the default black ...

What is the best way to incorporate a function within a $.click (jquery) event that utilizes an id directly from the clicked element?

It seems that my title may not be very clear, but I have a jQuery code snippet that is causing some issues. The problem stems from the fact that when I click on an image with the class 'slideimg', I expect a function named slideDo to be executed, ...

Can a CSS3 filter be utilized to transform gradient colors into solid colors?

I have an interesting scenario where I am using a -webkit-mask with a radial-gradient to create small dots on a background image. These dots are transparent, allowing the background image to show through. However, each dot has a gradient color within it. ...

What's preventing my code from running the CSS class properly?

I'm puzzled as to why the "grow" class for image pop up is not working even though it's included in the echo script. Here is the PHP code snippet: echo "<a href='$file'><img class='grow' src='$file' alt=&a ...

My React component seems to be unable to locate and process my CSS file

I am encountering an issue where my React Component is not recognizing my CSS file. Here is the code snippet from my React component: import React, { Component } from 'react'; import './Jumbotron.css'; class Jumbotron extends Compone ...

Adding multiple classes with jQuery and activating them using other jQuery functions

How can I use jQuery to add an active class to menu elements that have multiple classes? The code I have tried so far is not working as expected: JQUERY $('#foo_menu li a').click(function(){ $('#foo_menu li a').removeClass(&apos ...