J. Davidson
J. Davidson

Reputation: 3317

Returning column total using jquery function

In the following code, I am displaying columns with studentName and feeAmount. Then, at the end, I am trying to add the amounts of feeAmount, but the jQuery function is not returning total amount.

<div id="studentContent"  >
    <script id="studentTemplate" type="text/x-jquery-tmpl"> 
        <form id="studentForm" action ="">
            <table  class=""  border="1" cellpadding="0" cellspacing="0">
                <tbody>
                    {{#each items}}
                        <tr class="">
                            <td>{{=studentName}}</td>
                            <td><input type="text" class="{{=id}}" id="{{=id}}"
                   value='{{=feeAmount}}' /></td>
                        </tr>
                    {{/each}} 
                    <tr>
                        <td><input id="totalFeeAmount" value="a" /></td>
                    </tr>
                    <tr>
                </tbody>           
            </table>            
        </form>
    </script>
</div>

$(document).ready(function () {
    $("#studentForm").html(function () {
        var totalFeeAmount = 0;
        $(".feeAmount").each(function () {
            totalFeeAmount += parseInt($(this).html())
        });
        return totalFeeAmount;
    });
});

Please let me know how to fix the function to return and display the total of the column.

Upvotes: 1

Views: 73

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

You need to set the value of the totalFeeAmount input field instead of change the complete form content

$(document).ready(function () {
    $("#totalFeeAmount").val(function () {
        var totalFeeAmount = 0;
        $(".feeAmount").each(function () {
            totalFeeAmount += (parseInt($(this).html()) || 0)
        });
        return totalFeeAmount;
    });
});

or

$(document).ready(function () {
    var totalFeeAmount = 0;
    $(".feeAmount").each(function () {
        totalFeeAmount += (parseInt($(this).html()) || 0)
    });
    $("#totalFeeAmount").val(totalFeeAmount);
});

Upvotes: 1

Related Questions