I have the following code to simply change a Number value:
//zoom select
var zoom = 1;
$('select#zoom').change(function(e) {
zoom = $(this).val();
console.log('zooming to: ', Math.floor(zoom*100), '%');
});
//zoom incremental
$(document).keypress(function(e) {
//out
if(e.keyCode == 45){
if (zoom > 0) zoom = parseInt(zoom,10) - 0.1;
$('select#zoom').val(zoom);
console.log('zooming to: ', Math.floor(zoom*100), '%');
console.log('Type:',typeof zoom,' ',toString(zoom)); //*flag
}
//in
if(e.keyCode == 43){
if (zoom < 2) zoom = parseInt(zoom,10) + 0.1;
$('select#zoom').val(zoom);
console.log('zooming to: ', Math.floor(zoom*100), '%');
console.log('Type:',typeof zoom,' ',toString(zoom)); //*flag
}
});
It behaves as expected when the keypress event fires, however if I start with using the select element and then press a key to change the values, the output appears as such:
zooming to: 50%
zooming to: NaN%
Type: number [object Window]
HTML:
<select id="zoom">
<option value="2">200%</option>
<option value="1.5">150%</option>
<option value="1.25">125%</option>
<option value="1" selected>100%</option>
<option value=".75">75%</option>
<option value=".5">50%</option>
<option value=".25">25%</option>
</select>
This is driving me nuts. Any thoughts?
Thanks in advance.
1 Answer 1
Instead of parseInt, you should use parseFloat
parseInt(".25"); // returns NaN, because first char is not a valid char considering we are reading integer
parseFloat(".25") // returns 0.25
Also note that for integers (such as "2", "1") your solution works. It fails when trying to parse floats (".25")
Comments
Explore related questions
See similar questions with these tags.
zoom = $(this).val();. You should make sure it is a number at that point.zoom = parseInt($(this).val(), 10);but strangely enough it loses the value i.e perhaps convert it to undefined or null.zoom = $(this).val();saves a string, you need to convert it to a proper type of number - for sure it would be better to save it as a number at first place (when onchange is triggered), so you do not have to convert it over and over agian. For further info see my answer.