Andy Andy
Andy Andy

Reputation: 299

jQuery - add icon to select option based on value

I am currently trying to make any use of Polylang, a Wordpress plugin that allows to add language switcher to the website.

It currently generates simple select dropdown menu and changes the language upon selecting the language, so it's ok, however I am unable to style it properly - it's a raw dropdown menu.

I would like to add icons next to the displayed option, and as far as I know jQuery is my best shot here.

The issue I am having is that <option> tags are missing id or class tags, and it is impossible to add them without modifying the plugin itself.

Is it possible to create a jquery script that will display a flag next to the option based on it's value attribute?

Can you show me any example how to?

<select name="lang_choice" id="lang_choice">
<option value="en">English</option>
<option value="fr" selected="selected">French</option>
<option value="de">Deutsch</option>
</select>

Upvotes: 0

Views: 11172

Answers (2)

cari
cari

Reputation: 2300

SOLUTION 1 (Flags outside of the dropdown):

Try this:

$('<img class=flagicon src="'+$("select#lang_choice").val()+'.png">').insertAfter("#lang_choice");
$("select#lang_choice").change(function(){
    $(".flagicon").attr("src", $("select#lang_choice").val()+'.png');
});

The function assumes, that you have your flags named fr.png, de.png and en.png The first line adds the first icon, if no option has changed yet.

JSFiddle: http://jsfiddle.net/2j46orr4/1/

SOLUTION 2 (Flags inside the dropdown, every option has its own background-image): If you want to show the flag INSIDE the option, use a background-image:

CSS:

#lang_choice {
    background-repeat: no-repeat;
    background-image: url(/img/en.png);
    background-position: right center;
    padding-right: 20px;
}
#lang_choice option:nth-child(1) {
    background: url(/img/en.png) no-repeat right center;  
}
#lang_choice option:nth-child(2) {
    background: url(/img/fr.png) no-repeat right center;  
}
#lang_choice option:nth-child(3) {
    background: url(/img/de.png) no-repeat right center;  
}

jQuery:

$("select#lang_choice").css("background-image",'url(/img/'+$("select#lang_choice").val()+'.png)');
$("select#lang_choice").change(function(){
    $("select#lang_choice").css("background-image",'url(/img/'+$("select#lang_choice").val()+'.png)');
});

The flags have 16px margin on their right, so they are not hidden under the option arrow.

Demo: http://jsfiddle.net/2j46orr4/7/ (Chrome does not seem to render the option > background-image at the moment.)

Upvotes: 4

user3806613
user3806613

Reputation: 510

you can use a jquery plugin like this one.

HERE: http://designwithpc.com/Plugins/ddSlick#demo

Upvotes: 0

Related Questions