I've been trying to get this working for a few days now.. flabbergasted. I'm not an expert on JavaScript/jQuery AT ALL, so go easy, haha. ;-)
I have a dropdown with 9 values. I also have a span with a class set to 'option0'. The dropdown obviously has values ranging from 1 to 9. I want to change the class of the span when the dropdown is changed as well. If the dropdown is used and option 5 is selected, I want the span to have class 'option5'.
What would be the best way of doing this?
Thanks for reading, hope to hear from you guys soon. c:
$('select').change(function(){
var val = $(this).val();
alert(val);
$('span').removeAttr('class').addClass('option' + val);
})
http://jsfiddle.net/SAy7W/1/
<select id="your_select">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
<option>Option 5</option>
<option>Option 6</option>
<option>Option 7</option>
<option>Option 8</option>
<option>Option 9</option>
</select>
<span id="slave" class="option0">option0</span>
$('#your_select').on('change', function() {
var value = $('option:selected', this).text().replace(/Option\s/, '');
$('#slave').removeClass().addClass('option' + value).text('option' + value)
});
Working Demo 1
If you select
is like following:
<select id="your_select">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
<option value="option5">Option 5</option>
<option value="option6">Option 6</option>
<option value="option7">Option 7</option>
<option value="option8">Option 8</option>
<option value="option9">Option 9</option>
</select>
<span id="slave" class="option0">option0</span>
Then
$('#your_select').on('change', function() {
var value = this.value;
$('#slave').removeClass().addClass(value).text(value)
});
Working Demo 2
HTML:
<select id="master">
<option>Content 1</option>
<option>Content 2</option>
<option>Content 3</option>
<option>Content 4</option>
<option>Content 5</option>
<option>Content 6</option>
<option>Content 7</option>
</select>
<span id="slave">option0</span>
jQuery:
$('#master').change(function() {
var selected = $(this).val();
$('#slave').removeClass().addClass('option' + selected);
});
CSS:
.option0 {
background-color: red;
}
.option1 {
background-color: green;
}
.option2 {
background-color: brown;
}
.option3 {
background-color: yellow;
}
.option4 {
background-color: blue;
}
...
See a live example here
Alternatively, if you want to have any content between the option tags, apply a custom attribute 'data-position' and use this jQuery:
$('#master').change(function() {
var selected = $('#master option:selected').attr('data-position');
alert(selected);
$('#slave').removeClass().addClass('option' + selected);
});
See an updated live example here