Jim
Jim

Reputation: 1315

Adding two variables in js

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?

Upvotes: 1

Views: 157

Answers (6)

0x1gene
0x1gene

Reputation: 3458

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

Upvotes: 4

tymeJV
tymeJV

Reputation: 104775

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/

Upvotes: 3

samuke
samuke

Reputation: 460

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.

Upvotes: 0

Shijin TR
Shijin TR

Reputation: 7756

Use parseInt

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

Upvotes: 0

benzonico
benzonico

Reputation: 10833

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.

Upvotes: 0

Modestas Stankevičius
Modestas Stankevičius

Reputation: 144

var a = parseInt($('#net').val())+1

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

this should help.

Upvotes: 1

Related Questions