Implementing dynamic color blocks in a select2 multi-select feature for Laravel 5.2

I have a database where I store Hex color codes. My goal is to achieve something like this (or similar): https://i.sstatic.net/2PbXj.png https://i.sstatic.net/3SNP0.png

It should function properly when selecting the values and after they are selected.

In a regular multiselect, I am able to do the following:

<div class="col-sm-10">
<select id="colors" name="colors[]" multiple class="form-control">
  @foreach($colors as $key => $color)
    <option value="{{$key}}" style="background-color:{{$color->code}}"></option>
  @endforeach
 </select>
</div>

However, when using the Select2 plugin, the styles get overridden. I attempted to add a span or div inside the select-option like this:

<option value="{{$key}}"><span style="background-color:{{$color->code}}"></span>{{$color->code}}</option>

Unfortunately, this approach also gets overwritten.

I came across this example in the documentation, but I'm unsure how to adapt it for use with Laravel

function formatState (state) {
  if (!state.id) { return state.text; }
  var $state = $(
    '<span><img src="vendor/images/flags/' + state.element.value.toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>'
  );
  return $state;
};

$(".js-example-templating").select2({
  templateResult: formatState
});

Select 2 Version: 4.0.2

Answer №1

Customizing your dropdown menu is a breeze with the right classes and template functions. Check out this quick demo:

<select>
  <option>#232342</option>
  <option>#ffd800</option>
  <option>#ff1200</option>
</select>

<script type="text/javascript">
$(document).ready(function() {
  function formatColor (state) {
    if (!state.id) { return state.text; }
    var $state = $(
      '<span style="background-color: ' + state.text + '" class="color-label"></span><span>Color ' + state.text + '</span>'
    );
    return $state;
  };


  $('select').select2({
    width: "300px",
    templateResult: formatColor,
    templateSelection: formatColor
  });  
});
</script>

Check out the live demo here!

You can easily integrate this functionality into your Laravel project, just like in the provided code snippet.

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

Is there a way to merge the .load function and the document.referrer function together?

Is there a way to load a specific div from the previous page that a user originated from using a form? $(document).ready(function() { $("#div_to_be_populated").load('url #div'); }); How can I utilize the document.referrer function in the ur ...

Showing information retrieved from a database using PHP in a sequential manner

I'm currently working on developing a webpage that features 6 rows of images, with each row containing 4 images accompanied by captions right below them. The structure I have in mind is as follows: IMAGE IMAGE IMAGE IMAGE TEXT TEXT TEXT TEXT IMAGE ...

Error: Unable to access undefined properties (attempting to read 'getBoundingClientRect')

I keep encountering the issue TypeError: Cannot read properties of undefined (reading 'getBoundingClientRect') while working in React on my localhost with Node.js. I can't figure out what's causing it. import React,{useRef,useState} fro ...

"Encountered a roadblock while attempting to utilize the applyMatrix

I am currently working on running an animation using a JSON file and a custom JSON loader, not the one provided with three.js. Within the JSON file, there is an object called frames that contains multiple frames, each with shape information and a simulatio ...

The Bootstrap Library reference causes the anchor hover function to malfunction

Feeling frustrated after encountering an issue where the Bootstrap button class interferes with the hover function in standard CSS. Decided to create a custom solution by adding a grey box next to the button to display hover information instead of using t ...

Check email validity using jQuery and AJAX before form submission, then continue with AJAX submission

In order to ensure data integrity, the profile creation form on my website includes an email address field that must be in a valid format and not already in use. To validate the format, I utilize a client-side function called isValidEmailAddress. For the e ...

What are the steps for utilizing a button instead of an input field that is not within a form?

I need assistance with setting up a navbar with a button that will submit a form in the body with the ID of album_form. Can anyone provide suggestions for what to include in the onclick attribute to achieve this functionality? <body> <header& ...

Utilizing AJAX and JavaScript to create a countdown timer for a targeted HTML element

Here's a question broken down into two parts: I am looking to incorporate some JavaScript that triggers the #refresh function in order to display a count-up timer in text format. This timer should start at 0 seconds and run up to 3 minutes before ref ...

Removing a hyperlink and adding a class to a unordered list generated in JavaScript - here's how!

In my JavaScript code, I have the following implementation: init: function() { var html = []; $.each(levels, function(nr) { html.push('<li><a href="#">'); html.push(nr+1); ...

The HTML document declaration is missing an error

I encountered an error in my code, here is the snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1. ...

Modify the location of the input using jQuery

Hey there, I've got this snippet of HTML code: <div class='moves'> <div class='element'><input type='text' value='55' /></div> <input class='top' type='text&apo ...

Utilizing angularjs to send an image along with additional form fields to a spring rest service

I am looking to create a webpage that allows users to upload an image along with other form fields using AngularJS and Spring REST service. Below is the example of HTML code: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3 ...

Retrieving a list of selected items using React Material-UI

In my React + Material-UI frontend, there is a section where users can select items from a dropdown menu. I am looking for a way to capture the final list of items that the user selects, and allow them to delete items by clicking on a 'x'. How ca ...

ng-Mask: Enhancing String Operations

My goal is to only allow the input of uppercase characters as defined by the Mask. For example, using the mask code 'A' with regex [A-Z]. <input type="text" class="form-control" mask="AAAA"> I expect only uppercase characters in the range ...

The ng-bootstrap modal fails to appear when incorporating [formGroup]="FormName" or formControlName="elementName"

Utilizing ng-bootstrap to create a popup modal has been a challenge for me. When I import FormsModule and ReactiveFormsModule in src/app/modal-basic.module.ts, the code inside it looks like this: import { NgModule } from '@angular/core'; import { ...

CSS lacks hover effects for smooth transitions on mouse over and mouse out

When scrolling down, I've added a transition effect to smoothly change a div element. However, I want to avoid this transition effect when hovering over or moving the mouse out as the div is acting as a button. While I was successful in removing the e ...

The function string.charAt() is returning a value of 0

I'm attempting to output each letter of a word separately by using the variable string. Here is the code I have so far: function typewriter() { var el = document.getElementById("typewr"); var string = "Hello"; for(var i=0;i<string.le ...

A Guide on Modifying a Pseudo Element When Clicked

How can I create a click handler in jQuery to change the color of an 'eyebrow' element above a Heading element? The eyebrow element is set up with a pseudo element in my project, and I'm struggling to make it change color when the heading is ...

The Laravel system does not support calling the non-static method AppHttpModelsRole::id_role() in a static manner

Looking for assistance with creating a custom middleware in Laravel for login. I'm specifically trying to retrieve the Role using middleware, but running into some issues. class CheckRole { public function handle($request, Closure $next) { ...

What is the best way to access the element before and after a specific element in an array using JavaScript?

I need to create a function that accepts a string input, searches for its match in an array, and then returns the previous and next elements in the array. const array = [ "11111", "22222", "343245", "5455", "34999", "34 ...