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>
HMR
  • 37,593
  • 24
  • 91
  • 160
Phil Mulkins
  • 188
  • 1
  • 3
  • 10
  • 1
    Make a fiddle to get more responses ...!! – Prasath K Jun 25 '13 at 03:29
  • Do you have multiple input boxes with a dopricing class? – HMR Jun 25 '13 at 03: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). – Ken Herbert Jun 25 '13 at 03:36
  • total += parseFloat($(this).val()), 10; – Phil Mulkins Jun 25 '13 at 04: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. – Phil Mulkins Jun 25 '13 at 04:37

3 Answers3

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

isJustMe
  • 5,452
  • 2
  • 31
  • 47
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

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
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>
HMR
  • 37,593
  • 24
  • 91
  • 160
  • I do what the decimal but this code isn't not working. Is there something I am missing? I copied the javascript function. – Phil Mulkins Jun 25 '13 at 04:31
  • 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. – HMR Jun 25 '13 at 04:36
  • Do you have to have the ? – Phil Mulkins Jun 25 '13 at 04:39
  • @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. – HMR Jun 25 '13 at 04:44
  • I already have this and it doesn't work: (Doesn't show the http in the comment) – Phil Mulkins Jun 25 '13 at 04:47
  • You're doing something wrong, maybe copied something wrong. If the page loads jquery from the jquery site it should work fine. `` – HMR Jun 25 '13 at 04:51