I have a web page that allows a user to enter values into fields. When a user updates a field, I want to automatically update the total displayed to the user. Because the input fields are dynamically generated, I created a JavaScript function called "update". A sample of my code is shown here:
<input type="text" id="myField1" onchange="return update(this);" />
<input type="text" id="myField2" onchange="return update(this);" />
<span id="totalCount"></span>
var total = 0;
function update(e) {
var v = $(e).val();
if (parseInt(v) != NaN) {
total = total + v;
$("#totalCount").html(total);
}
return false;
}
When a user enters "2" into "myField1", "02" is displayed in the "totalCount" element. In reality, I would like to just display "2". How do I do this in JavaScript while taking into a account odd entries?
Thanks!
1 Answer 1
Since $(e).val() is a string, total + v is a string too. Use parseInt not just for the test but also when using the value:
var v = parseInt($(e).val(), 10);
if (!isNaN(v)) {
total = total + v;
$("#totalCount").html(total);
}
6 Comments
NaN != NaN returns true use isNaN(v);parseInt parses the input to integer. In case of 2.15 the output will be 2.
00or0?