roofdog
roofdog

Reputation: 361

Calculate the sum of multiple inputs with jQuery

I know questions of this nature have been asked on many occasions but after a few hours of trying out different things I am still none the wiser. Hopefully someone can enlighten me.

I am attempting to add the values of multiple inputs and output the total value in a separate field. The following snippet does the job but I need to loop through each season as they are dynamically created with different ids.

$('#season-0 .appearances').val(
    Number($('#season-4 .appearances').val()) +
    Number($('#season-36 .appearances').val())
);
$('#season-0 .goals').val(
    Number($('#season-4 .goals').val()) +
    Number($('#season-36 .goals').val())
);

I've tried a few different functions but nothing seems to be working, for example:

var sum = 0;
$('.appearances').each(function(){
    sum = sum + Number($(this).val());
});
$('#season-0 .appearances').html(sum);

I'd appreciate any help on this, it's been doing my head in for far too long now ;)

Here is the associated HTML:

<div id="season-0">
    <table>
        <tr>
            <td>
                <input type="text" data-index="appearances" class="appearances" value="" />
            </td>
            <td>
                <input type="text" data-index="goals" class="goals" value="" />
            </td>
        </tr>
    </table>
</div>
<div id="season-4">
    <table>
        <tr>
            <td>
                <input type="text" data-index="appearances" class="appearances" value="25" />
            </td>
            <td>
                <input type="text" data-index="goals" class="goals" value="4" />
            </td>
        </tr>
    </table>
</div>
<div id="season-36">
    <table>
        <tr>
            <td>
                <input type="text" data-index="appearances" class="appearances" value="19" />
            </td>
            <td>
                <input type="text" data-index="goals" class="goals" value="8" />
            </td>
        </tr>
    </table>
</div> 

Upvotes: 1

Views: 2671

Answers (1)

Abdullah Bakhsh
Abdullah Bakhsh

Reputation: 678

Oh I see, you're trying to display the sum in the first input box, to do that you must use val(sum), so here is the working solution:

var sum = 0;
$('.appearances').each(function(){
    sum += Number($(this).val());
});
$('#season-0 .appearances').val(sum);

Also, make sure you have properly linked the jQuery library.

Here is the fiddle:

http://jsfiddle.net/Ephws/

Upvotes: 3

Related Questions