Renay Renay - 1 month ago 12
Javascript Question

How to use operations based on the number of user inputs?

I am trying to make a simple calculator which tells students their average university mark based on their grades.

JSFiddle

I'm trying to get the formula to do this:

Step 1: (Mark * Credit Point)

Step 2: Add these totals together

Step 3: Get this total and divide it by the number of user inputs.

Having trouble with steps 2 and 3.
Right now when calculate is clicked, it just appends the single answer of each row one after the other. I want to add these values then divide it by the number of inputs.(As the amount of subjects will vary between users)

Any help is really appreciated.

HTML:

<div>
<table class='table'>
<tr>
<th> Unit Code </th>
<th> Mark </th>
<th> Credit Point </th>
</tr>
<tr>
<td> <input type="text"></td>
<td> <input type="text" class='mark'> </td>
<td> <input type="text" class='creditPoint'> </td>
</tr>
<tr>
<td> <input type="text"></td>
<td> <input type="text" class='mark'> </td>
<td> <input type="text" class='creditPoint'> </td>
</tr>
<tr>
<td> <input type="text"></td>
<td> <input type="text" class='mark'></td>
<td> <input type="text" class='creditPoint'> </td>
</tr>
</table>
</div>


Javascript:

$('#wam').click(function() {
$('.table tr').each(function() {
var mark = $(this).find('input.mark').val();
var cp = $(this).find('input.creditPoint').val();
var total = ((mark * cp));
// Find the total then divide by the number of entries

$('body').append(total);


});

});

Answer

You need to use a shared variable in the loop

$('#wam').click(function () {
    var total = 0,
        count = 0;
    $('input.mark').each(function () {
        var mark = this.value;
        var cp = $(this).parent().next().find('input.creditPoint').val();
        var t = mark * cp || 0;//if both the fields are not entered don't add them
        if (t) {
            //if the product is 0 then don't count the value
            count++;
        }
        total += t;
    });
    $('#total').text(total);
    $('#total2').text(count ? total / count : 0);//the ternary condition to prevent division by 0

});

Demo: Fiddle