0

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
  • When you input zero, does it display 00 or 0? Commented Nov 20, 2010 at 17:10

1 Answer 1

4

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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

Also NaN != NaN returns true use isNaN(v);
@Gumbo, what happens if he inputs a decimal, 2.15 for example?
@Marko: parseInt parses the input to integer. In case of 2.15 the output will be 2.
Yeah I thought so too, was just thinking it might be something to consider if decimal input is allowed :) +1 either way
Regarding decimals, you can use Number($(e).val()) instead of parseInt($(e).val(), 10)
|

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.