0

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.

asked Apr 8, 2015 at 21:53
4
  • Seems like this line is where the problem starts zoom = $(this).val();. You should make sure it is a number at that point. Commented Apr 8, 2015 at 21:56
  • I have tried using zoom = parseInt($(this).val(), 10); but strangely enough it loses the value i.e perhaps convert it to undefined or null. Commented Apr 8, 2015 at 21:59
  • 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. Commented Apr 8, 2015 at 22:03
  • @JanLegner That did it! Smart guy you are. TA Commented Apr 8, 2015 at 22:09

1 Answer 1

2

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")

answered Apr 8, 2015 at 21:59
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.