Ad

NaN In Javascript Showing Up When Using A Text Input Field

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>
Ad

Answer

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

Ad
source: stackoverflow.com
Ad