I am using a function where I have a readonly
text input
, and when I execute the function I want the number value + 1. So let's say I have 60, when I execute the function, the number returned should be 61.
But instead it's coming out 601, which is just adding the number 1 to the string. Any clue as to what is going on? Subtraction, multiplication and division all work fine. Here is a snippet
var num= $("#originalnum").val() + 1;
$("#originalnum").val(num);
And yes i've tried a few different variations, am I missing something?
If you don't like the above code spelling, you can try it this way too.
$("#originalnum").val(function() {
$(this).val(parseInt($(this).val()) + 1)
});
You should use the parseInt
function and make sure the value is number(use isNaN function):
var val = $("#originalnum").val();
var num = 0;
if ( !isNaN(val) )
num= parseInt(val) + 1;
A simple unary +
is sufficient to turn a string into a number in this case:
var num = +$("#originalnum").val() + 1;
$("#originalnum").val(num);
The problem is that .val()
returns the value of the element as a string, and when you use the +
operator on a string it does string concatenation. You need to convert the value to a number first:
var num = +$("#originalnum").val() + 1; // unary plus operator
// OR
var num = Number($("#originalnum").val()) + 1; // Number()
// OR
var num= parseFloat($("#originalnum").val()) + 1; // parseFloat()
// OR
var num= parseInt($("#originalnum").val(),10) + 1; // parseInt()
Note that if you use parseInt()
you must include the radix (10) as the second parameter or it will (depending on the browser) treat strings with a leading zero as octal and strings with a leading "0x"
as hexadecimal. Note also that parseInt()
ignores any non-numeric characters at the end of the string, including a full-stop that the user might have intended as a decimal point, so parseInt("123.45aasdf",10)
returns 123
. Similarly parseFloat()
ignores non-numeric characters at the end of the string.
Also if it's a user-entered value you should double-check that it actually is a number and perhaps provide an error message if it isn't.
When you use the *
, /
or -
operators JS tries to convert the string to a number automatically, so that's why those operators "work" (assuming the string can be converted).
Use parseInt()
:
var num= parseInt($("#originalnum").val(),10) + 1;
So your number is treated as an integer instead of a string (as .val()
treats the result as string by default)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With