1

I am not sure why, but I am having a serious issue trying to add 1 to a variable.

    net = $('#net').val()+1;
$('#net').val(net).change();

This results in 1 1 (I understand that this is just concatenating). The last line is to output it to my input field. if I do this:

    net = net+1;
$('#net').val(net).change();

I get NaN. When I try to use parseInt like this:

    net = net+1;
net = parseInt(net,10);
$('#net').val(net).change();

I still get NaN. Ihave looked at the other examples on SO that adress this problem, and they say to use parseInt(), which I did. What else can I try to get this to add 1 to the existing number and putit in my field?

1
  • What's the result of parseInt($('#net').val()) + 1 Commented May 22, 2013 at 13:12

6 Answers 6

4

try to do net = parseInt(net,10); first

then net = net+1;

In your code you do:

net = net+1; //from this point net=11
net = parseInt(net,10);

which is wrong, You should inverse your two statements

net = parseInt(net,10); //here net=1 (integer representation)
net = net+1; // the '+' between two integers will result in an addition and not a concatenation
Sign up to request clarification or add additional context in comments.

2 Comments

parseInt(net, 10) is the best answer so far, because it prevents odd edge cases where strings like "011" could be interpreted as 9
This is the one that finally did the trick. Thanks to ALL for your assistance and answers.
3

Try this:

net = +net + 1;
$("#net").val(net);

The + in front of your net variable casts this to a Number

Fiddle: http://jsfiddle.net/tymeJV/WudHW/1/

3 Comments

Still get NaN. Does the double quuotes make a difference?
@Jim keep a break point in your favourite browser developer tool and check where the problem is arising.
@Jim -- Before you do any math, can do do a quick alert(net) and verify that the net variable actually contains data?
1
var a = parseInt($('#net').val())+1

$('#net').val(a).change();

this should help.

Comments

0

Thing is your variable net is not a number but a string, you have to first parse it to an int :

net = parseInt($('#net').val());

And then do all the add you want.

Comments

0

Use parseInt

     net = parseInt($('#net').val())+1;
     $('#net').val(net).change();

Comments

0

It is because val() returns a string and you try to add 1 to a string, which contains number 1 and a space letter. Try for example

var net = +$.trim($('#net').val());
$('#net').val(net + 1).change();

This gets rid of the white space and casts net as a number before inserting it back to the input(?) field.

Comments

Your Answer

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.