How to add image or icon in select list with jQuery?
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?
- First thing is to hide the actual select element then get all the options of it.
- 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.
would this work with a datalist and setting the value on that? rather than a select
Definitely, abi
If you found any issue, please let me know, I’ll fix that