Reputation: 956
I am working with jQuery. I have created one form and its input field.
I have display input field value into lable and than want to get total sum of that lable. SO I have written code like below :
$("#band_members").keyup(function(){
var val = $(this).val();
if (!isNaN(val)){
var ttl_band = val*30;
$('label[for="' + this.id + '"]').text(ttl_band);
calculateSum();
}
});
$('#dj').change(function() {
var val = $(this).val();
if (!isNaN(val)){
$('label[for="' + this.id + '"]').text(val);
calculateSum();
}
});
$("#extra_round").keyup(function(){
var val = $(this).val();
if (!isNaN(val)){
var ex_round = val*100;
$('label[for="' + this.id + '"]').text(ex_round);
calculateSum();
}
})
And my calculateSum function is looks like below:
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
jQuery(".numLabel").each(function() {
//add only if the value is number
if(!isNaN(this.text) && this.text.length!=0) {
alert(this.text);
sum += parseFloat(this.text);
//console.log(sum);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
jQuery(".total_sum").html(sum.toFixed(2));
}
But here my function is not call. So what should I have to change in my jQuery?
Upvotes: 0
Views: 143
Reputation: 133453
Label doesn't have the text
property, So you need to use either $(this).text()
or this.textContent
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
jQuery(".numLabel").each(function() {
var text = $(this).text(); //this.textContent
//add only if the value is number
if (!isNaN(text) && text.length != 0) {
//alert(text);
sum += parseFloat(text);
//console.log(sum);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
jQuery(".total_sum").html(sum.toFixed(2));
}
Upvotes: 1