0

I have a form with four text input elements. Every time one of them is updated, I want the sum of the four text input boxes to be displayed in a div below without the user pushing a button. Here's what I have so far (I got the idea from here [does this only work with select?]):

var getSum = function() {
    var email = $('#emailDown').val();
    var internet = $('#internetDown').val();
    var server = $('#serverDown').val();
    var desktop = $('#pcDown').val();
    //TODO:Check for integers (not needed with sliders)
    var sum = email + internet + server + desktop;
    $('totalHoursDown').html(sum);
}
$('#emailDown').change(getSum(event));
$('#internetDown').change(getSum(event));
$('#serverDown').change(getSum(event));
$('#pcDown').change(getSum(event));

Currently, it's not updating. (Don't worry about validating). I'm new to PHP, so I'm not sure if I should be using it in this instance.

Community
  • 1
  • 1
SomeKittens
  • 38,868
  • 19
  • 114
  • 143

2 Answers2

6

You are missing a # or . in your selector, depending on if totalHoursDown is a class or an ID:

$('totalHoursDown').html(sum);

// Should be this if ID
$('#totalHoursDown').html(sum);
// or this if class
$('.totalHoursDown').html(sum);

Update:

I modified the code by jmar777 a bit to make it work. Try this instead:

$(function(){
    var $fields = $('#emailDown, #internetDown, #serverDown, #pcDown'),
    $totalHoursDown = $('#totalHoursDown');
    $fields.change(function() {
        var sum = 0;
        $fields.each(function() 
                 { 
                     var val = parseInt($(this).val(), 10);
                     sum += (isNaN(val)) ? 0 : val; 
                 });
        $totalHoursDown.html(sum);
    });
});

​Here is a working fiddle as well: http://jsfiddle.net/mSqtD/

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
1

Try this:

var $fields = $('#emailDown, #internetDown, #serverDown, #pcDown'),
    $totalHoursDown = $('#totalHoursDown');
$fields.change(function() {
    var sum = 0;
    $fields.each(function() { sum += $(this).val(); });
    $totalHoursDown.html(sum);
});

Also, in your example, you had $('totalHoursDown').html(sum);, which I'm assuming was intended to be an ID selector (i.e., $('#totalHoursDown').html(sum);.

jmar777
  • 38,796
  • 11
  • 66
  • 64