2

I am trying to use a simple function of javascript that was intended to be used with a SELECT dropdown with single digits, but now I need to use it for when visitors type in a value with decimal points. I am getting a NaN with the current javascript even when I type in 30 or any number. Any suggestions on how to get my total?

JAVASCRIPT:

$(function () {
    $('.DoPricing').change(function () {
        var total = 0;
        $('.DoPricing').each(function () {
            total += parseInt($(this).val());
        });
        $('#TotalPrice').html('$' + total);
    });
});

HTML:

<form action="myactionpage.php" method="POST">
<table>
  <tr>
    <td>How much will you be paying today?</td>
    <td>$<input type="text" name="howmuch" id="howmuch" placeholder="0.00" class="DoPricing"></td>
  </tr>
  <tr>
     <td><div class="totalbox">Total Amount Due Today: <strong><span id="TotalPrice">$0.00</span></strong></div>
     </td>
   </tr>
   <tr><td><input type="submit" id="submit" name="submit" value="Submit Payment" class="submitbut" /></td>
  </tr>
  </table>
 </form>
5
  • 1
    Make a fiddle to get more responses ...!! Commented Jun 25, 2013 at 3:29
  • Do you have multiple input boxes with a dopricing class? Commented Jun 25, 2013 at 3:35
  • Using parseInt() you should always pass a second argument to the function indicating the base you are using (for what you need parseInt($(this).val(), 10) otherwise an input of 08 and I think 09 will equate to zero (due to being read as an invalid octal number). Also if you require decimal values from your input, use parseFloat() instead of parseInt() (but note that parseFloat() does not take the base argument, it always works only in base 10 aka decimal). Commented Jun 25, 2013 at 3:36
  • total += parseFloat($(this).val()), 10; Commented Jun 25, 2013 at 4:36
  • That works but it doesn't work on the first entry. It comes up NaN. But if I put something in the second box or third, it will add them with decimals. Commented Jun 25, 2013 at 4:37

3 Answers 3

5

Try this:

$(function () {
    $('.DoPricing').on("keyup",function () {
        var total = 0;
        $('.DoPricing').each(function () {
            total += parseFloat($(this).val()) || 0;
        });
        $('#TotalPrice').html('$' + total);
    });
});

This accepts decimals now, here is the demo

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

Comments

2

Your basic example works for me. I'm guessing there are other elements on the page with class, but that don't necessarily have values, and that you'd like them to default to zero. When an input has no value, .val() returns the empty string, and parseInt('', 10) returns NaN, not 0, so you're not getting what you want.

This is very simple to fix:

total += parseInt($(this).val()) || 0;

Demo: http://jsfiddle.net/mattball/2rgku

2 Comments

This works fine, but it doesn't support decimal points. Is there a way to make it support decimals?
Use parseFloat instead of parseInt.
0

I assume you want decimals as well but you're using parseInt instead of parseFloat and if you're using decimals (because it's money) then you should use toFixed. In the following code I assume the user will use the . as a decimal symbol and there should be only one . in the value (no thousands separator).

In your for each you convert a perfectly good usable this to a jQuery object only to get the value. I've changed $(this).val() to this.value so the conversion isn't needed.

<!DOCTYPE html>
<html>
 <head>
<title>test</title>
     <script type="text/javascript" src="jquery-1.9.0.js"></script>
</head> 
 <body> 
<form action="myactionpage.php" method="POST">
<table>
  <tr>
    <td>How much will you be paying this morning?</td>
    <td>$<input type="text" name="howmuch" id="howmuch" placeholder="0.00" class="DoPricing"></td>
  </tr>
  <tr>
    <td>How much will you be paying this evening?</td>
    <td>$<input type="text" name="howmuch" id="howmuch1" placeholder="0.00" class="DoPricing"></td>
  </tr>
  <tr>
     <td><div class="totalbox">Total Amount Due Today: <strong><span id="TotalPrice">$0.00</span></strong></div>
     </td>
   </tr>
   <tr><td><input type="submit" id="submit" name="submit" value="Submit Payment" class="submitbut" /></td>
  </tr>
  </table>
 </form>

     <script type="text/javascript">
         (function () {
             function getValue(el) {
                 if (el.value === "") { return 0; }
                 var nr = parseFloat(el.value);
                 // only 0 to 9 or . and only one . used as decimal symbol
                 if (/[^0-9.]/.test(el.value) || /.*?\..*?\./.test(el.value)) {
                     return false;
                 }
                 return nr;
             }
             $('.DoPricing').on("keyup", null, null, function (e) {
                 var $this = $(this),
                 val = getValue(this),
                 total = 0;
                 if(val!==false){
                     $this.data("pref",val);
                 }else{
                     $this.val($this.data("pref")||"");
                 }
                 $('.DoPricing').each(function () {
                     total += parseFloat(this.value,10)||0;
                 });
                 $('#TotalPrice').html('$' + total.toFixed(2));
             });
         })();
     </script>
 </body>
</html>

6 Comments

I do what the decimal but this code isn't not working. Is there something I am missing? I copied the javascript function.
You can press F12 in the and check out the console both firefox and chome will tell you something useful, my guess is that the jQuery reference in the code doesn't actually point to the jQuery library.
Do you have to have the <script type="text/javascript" src="jquery-1.9.0.js"></script>?
@PhilMulkins in your sample code you use $(... all over the place, where do think that comes from? These functions are not standard JavaScript functions but come from the jQuery library. Your code wouldn't do anything without adding the jquery library and so won't mine because I assume you're including it in your page.
I already have this and it doesn't work: <script type="text/javascript" src="code.jquery.com/jquery-1.10.1.min.js"></script> (Doesn't show the http in the comment)
|

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.