Reputation: 53
I have a simple <select>
dropdown box with different font sizes and with that I am trying to change the font size of some text in a div with id="textDiv"
. But it isn't really working. I have never used element before so please help me out.
HTML
<select name="fontSize" size="1" id="sizeSelector">
<option value="" selected> 12px </option>
<option value="1"> 14px </option>
<option value="2"> 16px </option>
<option value="3"> 20px </option>
<option value="4"> 24px </option>
<option value="5"> 28px </option>
<option value="6"> 34px </option>
<option value="7"> 40px </option>
<option value="8"> 46px </option>
<option value="9"> 44px </option>
<option value="10"> 66px </option>
<option value="11"> 88px </option>
</select>
Jquery
$('select').change(function(){
var size = $(':selected').val();
$('#textDiv').css('font-size', size);
});
I am sure something is wrong with the Jquery logic. Thanks
Upvotes: 0
Views: 776
Reputation: 700182
You are getting all elements in the page that matches :selected
, so if you have any other dropdown before that, you would get the selected option from that instead first in the result. You can use this
as context to limit the search within the current dropdown.
You are getting the value from the option using the val
method, but the option isn't a form field, so you would use the attr
method to get the value
attribute:
var size = $(':selected', this).attr('value');
However, it's easier to get the value from the select:
var size = $(this).val();
You would make the values in the options correspond to the sizes, but if that is not possible, you would need to use the text of the option and ignore the value:
var size = $(':selected', this).text();
Upvotes: 2
Reputation: 16068
If you make a simple console.log(size)
, you will notice that you are picking the value of the option, not its text. You need to do this to select text:
var size = $(':selected').text();
Upvotes: 1
Reputation: 535
This one
$('select').change(function(){
var size = $(this).val();
$('#textDiv').css('font-size', size+'px');
});
Upvotes: 0