0

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)

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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)

3 Comments

Don't use parseInt without a radix, doubly so if you are dealing with user input.
@Quentin What if you want to support user input of both hex and dec? :)
@BarbaraLaird — Then that is best handled with a clear, radio button based, user interface :)

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.