Icon-enhanced Bootstrap dropdown selection

I have a unique select dropdown using Bootstrap where I want to display icons like the example below:

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

<!DOCTYPE html>
<html>
<head>
    <script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c1e1313080f080e1d0c3c49524e524e">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b4944445f585f594a5b6b1e05190519">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0">

    <script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<div class="input-group mb-3">
  <select class="form-select" id="inputGroupSelect03" aria-label="Example select with button addon">
  <img src="https://img.icons8.com/offices/30/null/form.png"/>
    <option selected>Choose...</option>
  <img src="https://img.icons8.com/offices/30/null/form.png"/>    
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
  </select>
</div>
</body>
</html>

Answer №1

If you want to customize your dropdown button to look like a select element, you can use your CSS skills to achieve that.

By setting a max-height and allowing overflow to scroll on the dropdown menu, it will behave like a select element for you.

I have made some modifications to your HTML by adding a little jQuery and CSS.

I have utilized attributes to include an image in each option, which is later displayed using jQuery in the dropdown list menu item.

There are also helpful comments in the code that may help you learn from this example.

Additionally, there are many plugins available that can provide the functionality you need and even more than that.

// JavaScript function to enhance select elements with images
function _smartSelectWithImage(select) {
  // Check if select element has already been initialized
  if (select.hasClass('initialized')) return;
  
  // Hide select element and mark it as initialized
  select.addClass('d-none initialized');
  
  let d = '<div class="dropdown u008">';
    d += '<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">Choose...</button>';
    d += '<ul class="dropdown-menu">';
    
  // Iterate through options of select element to gather necessary information
  select.find('>option').each(function(){
    let value = $(this).attr('value');
    let image = $(this).attr('data-image');
    let text = $(this).text();
    
    // Create menu item for dropdown if option has a value
    if (typeof value!=='undefined')
        d += '<li><a class="dropdown-item" href="javascript:void(0);" data-value="'+value+'"><img src="'+image+'" />&nbsp;'+text+'</a></li>';
  });
  d += '</ul></div>';
  let $html_d = $( d );
  
  // Insert newly created HTML after the select element
  $html_d.insertAfter(select);
  
  // Change select value on click and update selected item display
  $html_d.on('click', '.dropdown-menu>li', function(){
    select.val($(this).find('>a').attr('data-value'));
    
    console.log( "Selected", select.val() );
    
    $html_d.find('>button').html( $(this).find('>a').html() );
  });
}

// Initialize all select elements on page load
$(function(){
  $('body').find('select').each(function(){
    _smartSelectWithImage($(this));
  });
});
.u008.dropdown { width: 100%; position: relative; }
.u008 > button, 
.u008 > button:hover, 
.u008 > button:focus, 
.u008 > button:active {
  width: 100%; 
  background: transparent !important;
  color: #000 !important;
  text-align: left;
}
.u008 > .dropdown-menu {
  left: 0px !important;
  max-height: 200px;
  overflow-y: auto;
  overflow-x: hidden;
}
<!DOCTYPE html>
<html>
<head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0">
</head>
<body>
<div class="input-group mb-3">
  <select class="form-select" id="inputGroupSelect03" aria-label="Example select with button addon">
    <option selected>Choose...</option>
    <option value="1" data-image="https://img.icons8.com/offices/30/null/form.png">One</option>
    <option value="2" data-image="https://img.icons8.com/offices/30/null/form.png">Two</option>
    <option value="3" data-image="https://img.icons8.com/offices/30/null/form.png">Three</option>
  </select>
</div>
</body>
</html>

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

Preview of Hoverbox Caption

I'm working on a website using the Hoverbox image gallery (http://host.sonspring.com/hoverbox/) and I'm trying to include captions for each image preview that appears when hovering over the enlarged image. However, I am facing difficulty as I hav ...

Tips for escaping an infinite loop within the componentDidUpdate function in reactjs

Currently, I am working on creating dashboards using reactjs. I have successfully implemented 4 tabs or buttons for charts, but I am facing an issue when clicking on different dashboards that have the same chart in the same panel. The chart is not updating ...

"Redirecting to an HTML page from the POST method is not supported in the Flask backend and Vanilla JS frontend setup

Utilizing the selected dropdown value from the frontend to perform calculations on the backend, resulting in an HTML page being returned. It's worth noting that no response is needed from the POST method, such as using return jsonify. Currently, I am ...

Guide on sending a JavaScript function to a Pug file using Node.js and Express

In my recent project, I developed a node app using express along with a pug file. The express app is configured to listen on port 3000 and render the pug file. One of the key functionalities involves fetching information from an external API. My goal is to ...

The form within the while loop is only functioning with the initial result

Within a while loop, I have a form that is being processed with ajax. The issue is that it only works on the first form and not on the others. Can someone take a look? <?php while($a = $stmt->fetch()){ ?> <form method="post" action=""> ...

Is the term 'Literal' in Javascript Arrays simply referring to its dynamic nature, allowing it to be modified at any time?

I'm confused why Mozilla refers to this as an Array 'Literal' when it's declared using the VARIABLE keyword and its content can be modified... var drinks = ["Espresso", "Latte", "Cappuccino"]; Could someone shed some light on this for ...

Sticky header and a sidebar gallery with consistently sized thumbnails

Hello everyone, I'm stepping into the world of HTML and CSS with my first question. As a beginner, I find myself facing a challenge that seems to be beyond my current skill level. Here's the scenario: I want to create a webpage with a fixed left ...

What are some strategies for safeguarding a disabled button?

Is there a way to securely disable a button if the user does not have permission to access it? I currently disable it at the Page_Load event: Page_Load() { if(!userhasrights) { btn.Enabled=false; } } However, after rendering, ASP.N ...

Styling Based on Conditions in Angular

Exploring the unique function of conditional formatting in Microsoft Excel, where color bars are utilized to represent percentages in comparison to the highest value. https://i.sstatic.net/nTGCJ.png Is there a way to replicate this functionality using HT ...

When combining Symfony, Twig, and Semantic UI, users may encounter an issue where the background image fails to display

Can someone assist me in identifying the issue with my code? I am using Symfony 2.8, Semantic UI, and Twig, attempting to set a background image on my site. The modification is being made to my base.html.twig file. I have attempted: Using different ima ...

Incorporating a JavaScript workflow into Django

Currently, I am following a tutorial on integrating a modern JavaScript pipeline into my Django application. The objective is to have the JavaScript code write "Hello webpack" onto the page, but unfortunately, it is not displaying as expected. Since I alr ...

What is the best way to place a button within a line of text

I am trying to achieve a layout similar to this: -------------------button------------------ I can add text inside the line, but it doesn't look good when I add a button. Any suggestions on how I can improve this? ...

Preserve the timestamp of when the radio query was chosen

I'm interested in finding a way to save the user's selected answer for a radio button question and track the time they saved it. Is there a way to achieve this using HTML alone? Or would I need to utilize another coding language or package? Just ...

`Place the image in the middle of the page`

I'm attempting to align the image directly before the text within the same div. I've applied CSS with text-align:center to the div, but it only seems to affect the text. Any suggestions on how to position the image right before the text? http:// ...

The slideshow fails to show correctly after being loaded from an external JavaScript file

Utilizing standard code, I have set up a Slideshow at the top of a website: HTML: <body id="Top" onload="showSlides()"> ... <div id="slides"> <div id="slide1" class="slides fade"></div> <div id="s ...

What's the quickest method for duplicating an array?

What is the quickest method for duplicating an array? I wanted to create a game, but I found that Array.filter was performing too slowly, so I developed a new function: Array.prototype.removeIf = function(condition: Function): any[] { var copy: any[] ...

Pause the execution of an AJAX callback function after numerous AJAX requests

I have two separate Ajax calls in my code. Both of them have different callbacks that need to execute upon successful call. $.ajax({ type: 'POST', url: "url1", success: foo1 }); $.ajax({ type: 'POST', url: "url2", ...

Tips for sorting/merging/consolidating data in Angular

Take a look at this code snippet: rowData = [ [ '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2018-12-10 08:00:00' ...

prismjs plugin for highlighting code displays code in a horizontal format

If you're looking for a way to showcase source code on your website with highlighted syntax, prismjs.com may be just what you need. It offers a similar style to monokai... However, I've encountered an issue where the plugin displays my code in a ...

Using React to create a fadeout effect and decrease the length of the photo

Is there a way to create a fade-out effect for each photo card and then shorten the length of the photos following the fade out? I have tried implementing a solution, but it doesn't seem to work when I click on each photo. Any suggestions or insights ...