Diego Cespedes Diego Cespedes - 5 days ago 5
Javascript Question

Javascript math issue - attribute value attribute

i'm new in javascript code, i have simple question, i'm tryng to attribute new value to my input

<input id="rimonta" type="text" />
,

var p = listData.list[0].puntata; // this return 10
var x = p + 1 // i want have result 10+1 = 11
$('#rimonta').val(x); // actually it attribute value 101 and NOT 11


I don't know why the math 10 + 1 return 101 and NOT 11. Thank you for your help!

Answer

That is most likely due to the fact that p is a string

var p = "10";
var x = p + 1;
console.log(x) // returns 101

var p = 10;
var x = p + 1;
console.log(x) // returns 11

var p = "10";
var x = parseInt(p) + 1;
console.log(x) // returns 11