JavaScript

How to add image or icon in select list with jQuery?

Share your learning

Hey friends, Today I am going to show you how you can create a select box with an icon or images.

Actually, it’s a trick. A jQuery tricks

I have created a simple jQuery plugin for you. For more detail checkout GitHub repo.

How does this plugin work?

  1. First thing is to hide the actual select element then get all the options of it.
  2. Then it will create a button and a list of options. The button click will show this list otherwise, the list will be hidden. It will work like a dropdown menu. When the user clicks on the list item, it will assign the particular item to the button and value of list item to the select element.

How to use?

Step 1.

Create a select element with a unique id. If you want to add images as an icon to option list then add the image URL to data-icon attribute otherwise assign font-awesome icon class to data-icon like in given example:

<select id="example" name="currency">
<option value="btc" data-icon="btc.png"> Bitcoin (BTC) </option>
<option value="eth" data-icon="eth.png"> Ethereum (ETH) </option>
<option value="bch" data-icon="bch.png"> Bitcoin cash (BCH)</option>
</select>

Step 2.

Initialize the plugin like below:

$( selector ).IconSelectBox( isImage );
// isImage: boolean;

To add image isImage should be true and for icons it should be false;

Finally, you can get the value from your created select element. like if you create an element #select-action then you can get value like this

$('#select-action').val();

Nothing complicated.

Satpal

View Comments

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago