I built a quite complex form using for select option elements the jquery plugin sumoselect. I would need now to add an icon/image to each option. The image src would be a jpg file on my website.
Any chance to achieve this with sumoselect?
Thanks
EDIT I add that the image is variable and is depending on the "option" value.
Thanks to gaetanoM I elaborated a bit his snippet and came out with:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/HemantNegi/jquery.sumoselect@master/sumoselect.css">
<script src="https://cdn.jsdelivr.net/gh/HemantNegi/jquery.sumoselect@master/jquery.sumoselect.min.js"></script>
<select name="somename" class="testselect1">
<option value="1000">Volvo</option>
<option value="1001">Saab</option>
<option value="1002">Mercedes</option>
<option value="1003">Audi</option>
</select>
jquery:
$('.testselect1').SumoSelect();
$('.testselect1').on('sumo:opening', function(e) {
//console.log(e);
$(this).closest('.SumoSelect').find('.optWrapper li').each(function(idx, ele) {
console.log("idx",idx,"ele",ele);
//$(this).find('i').remove();
$(this).prepend('<img style="height:10px" '+
'src="https://www.freeiconspng.com/uploads/heart-png-15.png">');
$(this).prepend($('.testselect1 option').eq(idx).val());
$(this).find('label').css('display', 'inline');
})
})
For the sake of the example I used a fix image and an added text.
Looks good!
Thanks
EDIT 2
A small improvement to gaetanoM code is to add .opt : this will avoid adding images to the header of optgroup (in case it exists):
$(this).closest('.SumoSelect').find('.optWrapper li.opt').each(function(idx, ele) {
Another problem is that the image is not shown at first load but only on open and change...
I ended up for the moment with an ugly solution which consists in adding the image directly INSIDE the <option></option>.
To avoid showing the html with native select on mobile devices I've got a "checkmobile" function that put the image only on computer browsers.
In add to be ugly, this solution does not allow to see the image once selected with native mobile select and on pc it shows the html when hovering for "tips"....
Any easy way to have the image shown without checking any reload point?
Thanks again
You may add icons using the sumo:opening event. Using this event you can add icons to each list item and adjust the label style: