Reputation: 796
My select menu show the color name but with jQueryUI (custom.iconselectmenu) I like to add a avatar block with the corresponding color. I can't figure out how to add the two attributes:
data-class="avatar" data-style="background-image: none; background-color: (the rgb value)
in my code:
var data = [
{ text: 'Select a Color', value: '0' },
{ text: 'Antibes Green', value: 'rgb(95,173,72)' },
...
{ text: 'Versailles', value: 'rgb(206,204,130)' }
];
for(var j=0; j < data.length; j++) {
var d = data[j];
select.options.add(new Option(d.text, d.value))
}
Upvotes: 0
Views: 46
Reputation: 4443
Alternatively, you can use the setAttribute
method on the option, like this:
var option = new Option(d.text, d.value);
option.setAttribute('data-class', 'avatar');
option.setAttribute('data-style', 'background-image: none; background-color: ' + d.value);
select.options.add(option);
Here's a fiddle: https://jsfiddle.net/ad1no8ou/
My preference is to avoid creating HTML using string concatenation due to the risk of bugs when you inevitably forget to escape special characters in the values that you are concatenating.
Upvotes: 2
Reputation: 68393
Try replacing this line
select.options.add(new Option(d.text, d.value))
by
select.innerHTML += "<option value='" + d.text + "' data-class='avatar' data-style='background-image: none; background-color: (the rgb value)'>" + d.value +"</option>";
Upvotes: 1