I'll show you 2 solutions:
- one using your logic with an existent CSS
- One without CSS (! yes, without !)
Let's say you have a select name and options values like:
<select name="bg">
<option value="">Background</option>
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
</select>
<select name="color">
<option value="">Color</option>
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
</select>
We will retrieve the selects names and values (if there's one) and combine them inside an array like (example after selections):
["bg-red", "color-blue"]
now to set that array as class that means you have to prepare all those classes inside your CSS:
.bg-red{
background:red;
}
.bg-blue{
background:blue;
}
.bg-green{
background:green;
}
.color-red{
color:red;
}
.color-blue{
color:blue;
}
.color-green{
color:green;
}
Than we can use .attr('class', classesArr.join(' ')) to rebuild all the element's desired classes.
LIVE DEMO
function createClasses( element ){
var classesArr = []; // array to store all the classes
$('select').each(function(){
var myVal = this.value; // get the value // blue, red, green
if(myVal.length) // it there's a value join the value with the select name, ex: bg-blue, bg-red .... or color-blue, color-red ....
classesArr.push( this.name +'-'+ this.value );
});
console.log(classesArr); // open console to see what happens!
$(element).attr('class', classesArr.join(' ') ); // rebuild all the new classes
}
$("select").on("change", function(){
createClasses( "#arrowlink" ); // run function and pass as argument the desired element to play with
});
Edit: simplest solution!
As I don't know why you bother with all those classes I suggest you to remove headaches creating all those classes by using this simple trick:
LIVE DEMO
CSS:
NO CSS!!!!!
HTML:
<div id="arrowlink">ARROW LINK</div>
Please set:
<select name="background-color">
<option value="">Background</option>
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
</select>
<select name="color">
<option value="">Font Color</option>
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
</select>
<select name="font-size">
<option value="">Size</option>
<option value="9">9</option>
<option value="12">12</option>
<option value="18">18</option>
<option value="24">24</option>
</select>
create an object for the jQuery's .css() method exaple:
function createClasses( element ){
var classesArr = {};
$('select').each(function(){
var myVal = this.value ;
if(myVal.length) classesArr[this.name] = this.value;
});
console.log(classesArr);
$(element).css(classesArr);
}
$("select").on("change", function(){
createClasses( "#arrowlink" );
});
.val()as getter not as setter. Wrong. May we see some HTML please?nameand what you have insidevalplease show something