Reputation: 12487
I'm trying to set the colour of my text with class t1 with a colour value depending on what select option is chosen. This is the code I have got to:
$('#colour').on('change', function(){
$('.t1').css('color', ':selected").val()');
});
<select id="colour">
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="pink">Pink</option>
</select>
Even if I try with something like this it doesn't work:
$('#colour').on('change', function(){
$('.t1').css('color', 'red');
});
Upvotes: 0
Views: 48
Reputation: 490
It's working when you add your code to the onchange
event of HTML.
function onchangeevent(){
$('.t1').css('color', 'red');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="colour" onchange="onchangeevent()">
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="pink">Pink</option>
</select>
<div class="t1">
text
</div>
Upvotes: 1
Reputation: 41893
I would suggest you to catch the current selection of the select-box
with .val()
function.
this
keyword refers to the select-box
while the val()
function is displaying actual selection.
$('#colour').on('change', function() {
$('.t1').css('background', $(this).val());
});
.t1 {
height: 100px;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="colour">
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="pink">Pink</option>
</select>
<div class='t1'></div>
Upvotes: 1
Reputation: 1074168
Within an event handler callback for a form field, this
refers to the field. So $(this).val()
gives you the value:
$('#colour').on('change', function() {
$('.t1').css('color', $(this).val());
});
<select id="colour">
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="pink">Pink</option>
</select>
<div class="t1">I'm a t1</div>
<div class="t1">So am I</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1