Question

I'm using datatables to list different funds people can donate to. There is a plus icon for each one. Once they click the plus icon, it creates two new input fields. One of the new input fields is the name of the fund, which is readonly, the other is for the amount the person would like to donate to that fund. I need to add up all of the amount fields, to display the total amount, but I'm getting NaN.

$(document).ready(function() {
i = 0;
$(".addButton").click(function() {
    var a = $("td:first", $(this).parents("tr")).text();
    i = i + 1;
    $("#donateFunds").append("<div class='fundLine'><span class='d'>Name:</span> <input class='e' id='funds" + i + "' size='60' type='text' name='funds[]' value='" + a + "' readonly> <span class='d'>Amount:</span><input class='user_defined' id='fundAmt" + i + "' type='text' name='fundAmt[]' size='5' value=''> <img alt='Remove Fund' class='removeFund' src='/assets/images/delete.png'></div>");
});
$("body").on('click', '.removeFund', function() {
    $(this).closest("div.fundLine").remove();
});
$("body").on("keyup", ".user_defined", function() {
    var sum = 0;
    $(".user_defined").each(function() {
        //sum =+ parseFloat(this.value);
        //console.log(this.id);
        sum =+ parseFloat($(this.id).attr("value"));
        //sum =+ $(this).val();
        console.log($(this.id).attr("value"));
        //console.log(this.value);
        //console.log(this.value.length);
        //console.log(this.value.type);
    });
    $("#totalDonation").attr("value", sum);
    //console.log(sum);
});

});

Was it helpful?

Solution

Your code isn't working due to:

$(this.id).attr("value");

So this is saying $(yourElement) instead of $('#yourElement')

Try:

var sum = 0
$("body").on("keyup", ".user_defined", function() {
    sum = 0;

    $(".user_defined").each(function() {
        sum += parseFloat($(this).val());
    });

    $("#totalDonation").val(sum);
});

Also considering you're doing this on every key up, I'd remove the slow .each and do:

var sum = 0;
var $userDefined;

$("body").on("keyup", ".user_defined", function() {
    sum = 0;
    $userDefined = $(".user_defined"); // This can go outside the keyup if this list will never change.

    for(var i = 0; i < $userDefined.length; i++) {
         sum += parseFloat($userDefined[i].val());
    }

    $("#totalDonation").val(sum);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top