5

I wanna make form in which I have 7 input fields in which I'm entering numbers and one last input fields where all inserted numbers are summed in one result. I've tried to edit some script from other stacker but from some reason it doesn't display the result.

the html is:

<form class="form-horizontal" id="whereEntry" method='post' action=''>
   <fieldset>
    <input type="text" class="income_count span1 register_input" id="income" name="income" placeholder="% of income"> <br>
    <input type="text" class="income_count span1 register_input" id="income_2" name="income_2" placeholder="% of income"> <br>
<input type="text" class="income_count span1 register_input" id="income_3" name="income_3" placeholder="% of income"> <br>
<input type="text" class="income_count span1 register_input" id="income_4" name="income_4" placeholder="% of income"> <br>
    <input type="text" class="income_count span1 register_input" id="income_5" name="income_5" placeholder="% of income"> <br>
        <input type="text" class="income_count span1 register_input" id="income_6" name="income_6" placeholder="% of income"> <br><br><br>

   <input type="text" class="span2 register_input" id="income_sum" name="income_sum" placeholder="% of income"> <br>
       </fieldset>
       </form>

and my script so far looks like this:

var $form = $('#whereEntry'),
$summands = $form.find('.income_count'),
$sumDisplay = $('#income_sum');

$form.delegate('.income_count', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
    var value = Number($(this).val());
    if (!isNaN(value)) sum += value;
});

$sumDisplay.text(sum);
});

here is jsfiddle of it: http://jsfiddle.net/bT4nm/1/

could you help me? is the problem in my html classes or something in the script I'm nooby about jQuery and i need as ASAP solution.. update of my js fiddle would be great

dzordz
  • 2,277
  • 13
  • 51
  • 74
  • Once you get the numbers summing up correctly, you might have difficulty getting the total to display with the correct format (thousand separators, decimals places, currency symbol, etc). See this answer for help with that: http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript/28378652#28378652 – cssyphus Feb 07 '15 at 04:48

2 Answers2

5

do

$sumDisplay.val(sum);

instead of

   $sumDisplay.text(sum);

WORKING DEMO

bugwheels94
  • 30,681
  • 3
  • 39
  • 60
5

Use this:

var $form = $('#whereEntry'),
$summands = $form.find('.income_count'),
$sumDisplay = $('#income_sum');

$form.delegate('.income_count', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
    var value = Number($(this).val());
    if (!isNaN(value)) sum += value;
});

$sumDisplay.val(sum);
});