我使用数据表列出了人们可以捐赠的不同资金。每个都有一个加号图标。一旦他们点击加号图标,它就会创建两个新的输入字段。其中一个新的输入字段是基金的名称,只是该基金的名称,另一个是该人愿意捐赠给该基金的金额。我需要将所有金额字段相加,以显示总金额,但我得到了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);
});
});
答案 0 :(得分:0)
由于以下原因,您的代码无效:
$(this.id).attr("value");
所以这是$(yourElement)
而不是$('#yourElement')
尝试:
var sum = 0
$("body").on("keyup", ".user_defined", function() {
sum = 0;
$(".user_defined").each(function() {
sum += parseFloat($(this).val());
});
$("#totalDonation").val(sum);
});
同样考虑到你在每个按键上执行此操作,我会移除慢.each
并执行:
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);
});