A guide on using jQuery to include an icon within a select option

I'm having trouble adding an icon to a select dropdown using jQuery. I attempted to include the icon within the option itself, but it displays as empty boxes. Additionally, I want the selected option's icon to appear above without the accompanying text when clicked.

Here is the JavaScript:

<script>

$('select').each(function(){
    var $this = $(this), numberOfOptions = $(this).children('option').length;
  
    $this.addClass('select-hidden'); 
    $this.wrap('<div class="select"></div>');
    $this.after('<div class="select-styled"></div>');

    var $styledSelect = $this.next('div.select-styled');
    $styledSelect.text($this.children('option').eq(0).text());
  
    var $list = $('<div />', {
        'class': 'select-options'
    }).insertAfter($styledSelect);
  
    for (var i = 0; i < numberOfOptions; i++) {
        $('<div />', {
            text: $this.children('option').eq(i).text(),
            rel: $this.children('option').eq(i).val()
        }).appendTo($list);
    }
  
    var $listItems = $list.children('div');
  
    $styledSelect.click(function(e) {
        e.stopPropagation();
        $('div.select-styled.active').not(this).each(function(){
            $(this).removeClass('active').next('div.select-options').hide();
        });
        $(this).toggleClass('active').next('div.select-options').toggle();
    });
  
    $listItems.click(function(e) {
        e.stopPropagation();
        $styledSelect.text($(this).text()).removeClass('active');
        $this.val($(this).attr('rel'));
        $list.hide();
        //console.log($this.val());
    });
  
    $(document).click(function() {
        $styledSelect.removeClass('active');
        $list.hide();
    });

});</script>
<style>
    

 .select-hidden {
     display: none;
     visibility: hidden;
     
}
 .select {
    -webkit-font-smoothing: antialiased;
color: rgba(0,0,0,0.87);
font-family: Roboto,RobotoDraft,Helvetica,Arial,sans-serif;
text-size-adjust: 100%;
-webkit-tap-highlight-color: transparent;
margin: auto 0;
margin-top: 14px;
}
 .select-styled {
-webkit-font-smoothing: antialiased;
font-family: Roboto,RobotoDraft,Helvetica,Arial,sans-serif;
text-size-adjust: 100%;
transition: background .3s;
border: 0;
border-radius: 3px;
color: #444;
cursor: pointer;
display: inline-block;
font-size: 14px;
font-weight: 500;
outline: none;
position: relative;
text-align: center;
-webkit-tap-highlight-color: transparent;
width: 56px;
}
 .select-styled:after {
     content: "";
     width: 0;
     height: 0;
     border: 7px solid transparent;
     border-color: #546e7a transparent transparent transparent;
     
     top: 16px;
     right: 40px;
}
 .select-styled:hover {
     background-color: #eeeeee;
}
 .select-styled:active, .select-styled.active {
     background-color: #AFA7A7;
}

 .select-options {
     -webkit-font-smoothing: antialiased;
font-family: Roboto,RobotoDraft,Helvetica,Arial,sans-serif;
text-size-adjust: 100%;
color: #444;
cursor: pointer;
font-size: 14px;
font-weight: 500;
text-align: center;
-webkit-tap-highlight-color: transparent;
transition: opacity .1s linear;
background: #ffffff;
border: 0;
box-shadow: 0 8px 10px 1px rgba(0,0,0,0.14),0 3px 14px 2px rgba(0,0,0,0.12),0 5px 5px -3px rgba(0,0,0,0.2);
outline: 1px solid transparent;
overflow: hidden;
overflow-y: auto;
position: fixed;
z-index: 2000;
opacity: 1;
min-width: 56px;
top: 151px;
list-style: none;
}
 .select-options div {
    -webkit-font-smoothing: antialiased;
font-family: Roboto,RobotoDraft,Helvetica,Arial,sans-serif;
text-size-adjust: 100%;
-webkit-tap-highlight-color: transparent;
border-color: transparent;
list-style: none;
overflow: hidden;
position: relative;
text-align: left;
white-space: nowrap;
color: rgba(0,0,0,0.87);
font-size: 14px;
font-weight: 400;
cursor: pointer;
height: auto;
padding-right: 26px;
padding-left: 48px;
border-style: dotted;
border-width: 1px 0;
outline: 1px solid transparent;
padding-top: 14px;
padding-bottom: 14px;
}
 .select-options div:hover {
     
     background: #eeeeee;
}
    .sp{text-size-adjust: 100%;
list-style: none;
text-align: left;
white-space: nowrap;
cursor: pointer;
color: #546e7a;
-webkit-tap-highlight-color: transparent;
font-family: 'Material Icons Extended';
font-weight: normal;
font-style: normal;
letter-spacing: normal;
text-rendering: optimizeLegibility;
text-transform: none;
display: inline-block;
direction: ltr;
font-feature-settings: 'liga' 1;
-webkit-font-smoothing: antialiased;
font-size: 19px;
line-height: 19px;}
    </style>

HTML

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>


<select id="mounth">
    
    <option value="Left align" > &#xe236; Left align </option>
    <option value="Center align"><span class="sp"><i class="material-icons">&#xe235;</i></span> Center align</option>
    <option value="Right align">&#xe237; Right align</option>
    <option value="Justify">&#xe235; Justify</option>
</select> 

</body>
</html>

Answer №1

If you're looking to enhance your user experience, I suggest implementing selectBox. This will give you the flexibility to personalize a range of CSS styles, including icons - https://github.com/marcj/jquery-selectBox

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

Implementing a personalized filter onto the footer of an AngularJS UI Grid

After successfully creating a custom filter for my ui-grid that limits decimal numbers to two places and exporting it as a pdf using ui-grid-exporter, I encountered an issue. The filter works fine when exporting the main ui-grid but fails to apply within t ...

Number of TCP connections socket.io is utilizing with namespaces

While working with my express app, I came across an interesting code snippet: Here's the backend express server: io.on('connection', (socket) => { ...logic... }); const nsp = io.of('/my-namespace'); nsp.on('connection ...

What are the steps to modify or remove a node in react-sortable-tree?

I am currently working on implementing a drag and drop tree view using react-sortable-tree. Along with that, I also need to incorporate CRUD operations within the tree view. So far, I have been successful in adding, editing, and deleting nodes within the p ...

Unexpected gap located at the top of the div

I am experiencing two perplexing issues with my website. The first problem involves text overlapping and extending beyond the content area. I have tried using the break-word property to address this issue, but unfortunately, the bug seems to be originating ...

Testing Angular Reactive Forms: Synchronizing HTML and Control values mismatch

I have been diligently following the Angular reactive form unit testing tutorial here, but I continue to struggle with keeping the control value and HTML value in sync. Below is how I've implemented it; note that I am trying to use setValue along with ...

Ionic: How come my image is not loading with HTTP.GET?

I have been attempting to populate a gallery in my Ionic application by fetching images from a JSON file, but I am encountering issues. While following a guide on creating a grid-like image gallery using the Ionic framework (https://blog.nraboy.com/2015/03 ...

Nesting ng-repeat within another ng-repeat for dynamic content generation

I am currently working on a page that requires displaying boxes (using ng-repeat) containing information about channels and their corresponding cities. The issue I am encountering arises when repeating the second ng-repeat: <table class="table table-c ...

Node.js and Express: accessing req.body yields undefined value

In the midst of creating a basic browser application using Express, I encountered an issue when attempting to retrieve the value selected by a user from a dropdown menu. I assigned individual values to each option and set the form method to /post. However, ...

The POST request functions flawlessly on the local server, but encounters issues once deployed to Google Cloud Platform

Even though the Axios post request works fine on my local server, it throws a 404 not found error after I deploy the project on Google Cloud. On localhost, all requests are directed to URLs starting with http://localhost:9000/api/..., handling post reques ...

Ways to define properties in backbone entities

As I work on my app using backbone, I'm encountering a challenge that might be due to a misunderstanding on my part. I am trying to set specific attributes like titles while also having default values in place. However, it seems that the custom attri ...

"The utilization of either Threejs ArrowHelper or Line with an outlined design

Is there a way to outline an arrow or line using the ArrowHelper or Line geometries within the Three.js framework? While trying to achieve this, I encountered the issue that outlining a complex object or a line is not as straightforward as shown in this e ...

Inconsistent reliability of Loopback-context prompts the search for an alternative solution

After encountering some reliability issues with the loopback-context package, I decided to try an alternative approach. Instead of relying on setting the current user object in my middleware using loopback-context, I opted to fetch the accessToken from the ...

Using Typescript to implement a conditional return type and ensuring that the value types are consistent together

I am working with a useSelectedToggle hook that helps in connecting the UI state to the open/closed status of a dialog where it will be displayed. The toggle defines the value as (T) when it is open, and null when it is closed. How can I enforce stricter ...

Updating the minimum date based on the user's previous selection using React JS and Material UI

In my material UI, I have two date pickers set up: From Date - <KeyboardDatePicker value={initialDateFrom} disableFuture={true} onChange={handleFromDateChange} > </KeyboardDatePicker> To Date - <KeyboardDatePicker value={initialDateTo} ...

Utilize Material UI's Datagrid or XGrid components to customize the rendering

There is a section from Material UI discussing renderHeader in the DataGrid and Xgrid components. https://material-ui.com/components/data-grid/columns/#render-header The documentation describes how to add additional content to the header, but what if I w ...

Eradicating Pinpointers on Navigation Tool (Google Maps)

I have a feature that utilizes an ajax request to generate a marker or multiple markers when the user interacts with the map. Once a marker is created at a specific location by the user, I then set up a click event on the marker itself. The issue arises w ...

Error occurs when attempting to change the color of a dynamically generated div, resulting in the message: "Type Error: Unable to assign a value to the property '

I'm facing an issue with my code where I have a parent div that loads with a random color, and upon clicking a button, it should create a new colored div inside. However, I keep encountering the following error: TypeError: Cannot set property ' ...

Any suggestions on how to address vulnerabilities in npm when upgrading the main dependency version is not an option?

I recently ran the npm audit --production command and found a high-risk vulnerability related to the snowflake-sdk dependency. After checking the snowflake github page, I noticed that the package.json file includes "requestretry": "^6.0.0&qu ...

Issue with hashtag in regular expressions

Looking for a way to identify and link hashtag words with an anchor tag? Here's a snippet showcasing the concept: <p class="display"></p> var content = "I enjoy #blueSky. My favorite color is #green. #sky is amazing"; ...

What are the steps for utilizing the skrollr library to manipulate text within a div without it being

I'm a beginner in html, css, and javascript and I'm trying to create my first one-page website using the skrollr library. However, I'm facing an issue where the content in my second div is not displaying properly and is hidden behind the fir ...