javascript - jQuery - add icon to select option based on value -
i trying make use of polylang, wordpress plugin allows add language switcher website.
it generates simple select dropdown menu , changes language upon selecting language, it's ok, unable style - it's raw dropdown menu.
i add icons next displayed option, , far know jquery best shot here.
the issue having <option> tags missing id or class tags, , impossible add them without modifying plugin itself.
is possible create jquery script display flag next option based on it's value attribute? 
can show me 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>      
solution 1 (flags outside of 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, have flags named fr.png, de.png , en.png first line adds first icon, if no option has changed yet.
jsfiddle: http://jsfiddle.net/2j46orr4/1/
solution 2 (flags inside dropdown, every option has own background-image): if want show flag inside option, use 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 right, not hidden under option arrow.
demo: http://jsfiddle.net/2j46orr4/7/ (chrome not seem render option > background-image @ moment.)
Comments
Post a Comment