Reputation: 107
I'm trying to create a dropdown that will show google fonts for a customization website. I'm trying to apply a class to each option based on the option value. I can't just hard code it because I am working with a hosted vendor so I only have jquery/javascript abilities (otherwise I'd just add the class tag manually). Here's my HTML:
<select name="SELECT___ENG_SVC___52">
<option value="1167">Lobster</option>
<option value="1168">Shadows Into Light</option>
<option value="1169">Pacifico</option>
</select>
CSS:
.1167 {
font-size: 25px;
font-family: 'Lobster';
}
.1168 {
font-size: 25px;
font-family: 'Shadows Into Light';
}
.1169 {
font-size: 25px;
font-family: 'Shadows Into Light';
}
For my jquery/javascript, I have:
var fontname = element.options.val();
if(fontname == 1167) {
fontname.addclass(fontname.val);
}
What I'm trying to accomplish:
<select name="SELECT___ENG_SVC___52">
<option value="1167" class="1167">Lobster</option>
<option value="1168" class="1168">Shadows Into Light</option>
<option value="1169" class="1169">Pacifico</option>
</select>
fiddle: http://jsfiddle.net/sNkDW/276/
Any help would be much appreciated. Thanks in advance
UPDATE: oops, can't have class names that start with numbers. so lets make them .f1167 .f1168 and so on. can we have the jquery add an "f" in front of the option value to make it the class name?
Upvotes: 0
Views: 3029
Reputation: 4259
Try this in your script:
$(document).ready(function () {
$("#drd option").each(function () {
debugger;
$(this)[0].className = $(this)[0].value;
});
});
and change your HTML to:
<select name="SELECT___ENG_SVC___52" id="drd">
<option value="1167">Lobster</option>
<option value="1168">Shadows Into Light</option>
<option value="1169">Pacifico</option>
</select>
Upvotes: 0
Reputation: 18233
The jQuery addClass
method has an overloaded method which accepts a function as a parameter. You can leverage that to set the class for all of the elements at once:
$(function() {
$('select[name="SELECT___ENG_SVC___52"] option').addClass(function() {
return 'f' + $(this).val();
});
});
Upvotes: 3
Reputation: 3228
Since you have jquery
, you can try this;
$( "select[name='SELECT___ENG_SVC___52'] option" ).each(function() {
$(this).addClass(this.value);
});
Thanks!
Upvotes: 0
Reputation: 20636
Your fiddle has many errors. jQuery reference was not included.
Use .each()
.
$('select option').each(function(){
$(this).addClass(this.value);
});
Upvotes: 0
Reputation: 2907
try this:
var options=$("select option");
for(var i=0; i<options.length;i++){
$(options[i]).addClass($(options[i]).val());
}
Upvotes: 0
Reputation: 21
Please see edited code. I am using jQuery.
$("#myselect").children("option").each(function(index) {
$(this).addClass($(this).val());
});
http://jsfiddle.net/sNkDW/279/
Upvotes: 1
Reputation: 1481
try this:
$('option').each(function(){
var option = $(this);
var val = option.val();
option.addClass(val);
});
Upvotes: 0