Blynn
Blynn

Reputation: 1411

jquery adding input val together

For some reason my code returns "0111" when the returned value should be 3 adding the numbers together.

Is there a better way to write this so it adds the value of the input text?

var p = $(".p").val(); 
var r = $(".r").val();
var d = $(".d").val();
var s = $(".s").val();

var checkability = p + r + d + s;

alert(checkability)

Upvotes: 0

Views: 114

Answers (3)

Barbara Laird
Barbara Laird

Reputation: 12717

Use parseInt to make them integers

var p = parseInt($(".p").val(),10); 
var r = parseInt($(".r").val(),10);
var d = parseInt($(".d").val(),10);
var s = parseInt($(".s").val(),10);

var checkability = p + r + d + s;

alert(checkability)

Upvotes: 0

j08691
j08691

Reputation: 207901

Sure, the easiest thing is to coerce the string values into integers like:

var p = +$(".p").val(); 
var r = +$(".r").val();
var d = +$(".d").val();
var s = +$(".s").val();

jsFiddle example

You could also use the longer parseInt() function like var p = parseInt( $(".p").val(), 10);

Upvotes: 0

PSL
PSL

Reputation: 123739

You are concatenating strings you need to cast it to numeric. val() return data as string, or explicitly use parseInt(var, 10) or parseFloat based on your type.

Simple way is t use unary + operator prefixing the variable:

var checkability = +p + +r + +d + +s;

Fiddle

Upvotes: 3

Related Questions