Reputation: 43
I'm at a loss, I'm trying to allow users to select the font-family of some text output. The code basically boils down to this:
<div id='output'>
The quick brown fox jumps over the lazy dog
</div>
<select id='font-select'>
<option value='Lucida Console'>Lucida Console</option>
<option value='Courier New'>Courier New</option>
<option value='Consolas'>Consolas</option>
</select>
With jquery as follows:
$(document).ready(
function()
{
$('font-select').on( 'change',
function()
{
$('output').css( 'font-family', $('#font-select').val() );
console.log( 'Font changed' );
});
});
I know the on-change event fires every time I select a different font, but the font in the div only changes the first time I choose one. After that I still get a 'font changed' notice in the console, but no actual change in the #output div.
I've tried changing it to
$(document).on( 'change', '#font-select',
....
I've also tried changing the id's to classes and selecting via class
$('.font-select').change(
....
With the same results. Does anyone have any advice?
Upvotes: 0
Views: 147
Reputation: 15786
You didn't specify the id's correct in your jQuery (# missing).
$(document).ready(function() {
$('body').on('change', '#font-select', function() {
$('#output').css('font-family', $('#font-select').val());
console.log('Font changed');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'>
The quick brown fox jumps over the lazy dog
</div>
<select id='font-select'>
<option value='Lucida Console'>Lucida Console</option>
<option value='Courier New'>Courier New</option>
<option value='Consolas'>Consolas</option>
</select>
Upvotes: 1
Reputation: 1025
first i would always use the right selectors in jquery in your case use:
$('#font-select').on('change', function() {
$('#output').css[....]
}
The '#' selects by id.
Second tip:
Try removing the font-family class first and then set a new one, sometimes jQuery/html gets confused when you set values to already existing properties (or at least i have the feeling it does :D ) So try something like this in your "change" function:
$('#output').css('font-family', ''); //this is basically standard but i dont like it...
$('#output').css( 'font-family', $('#font-select').val() );
Upvotes: 1
Reputation: 4412
The issue is about the selectors you used. When you are trying to access element through id then you are suppose to add # in front.
Here is [fiddler][1] which works fine and solve your issue
Hope it helps.
[1]: https://jsfiddle.net/rajsnd08/nfh5craz/
Upvotes: 1