I have several text fields
<input class="add" type="text">
<input class="add" type="text">
<input class="add" type="text">
<input class="add" type="text">
<p id="total"></p>
The values in each field are added dynamically by a PHP script when the page is loaded but the user has the option to edit them. I have been trying to figure out a way to add up all the values using javascript and output them into the #total p tag. I have found a few scripts arround and tried writing one myself but it didnt seam to work.
The best I found looked like this....
function addAll() {
var sum = ""
var values = $('.add').each(function(){
sum += isNaN(this.value) || $.trim(this.value) === '' ? 0 : parseFloat(this.value);
});
$('#total').text(sum);
}
$('.add').keyup(displayTotal);
But that didn't output anything
Am I doing anything seriously wrong?
Cheers
addAll()but your keyup event is calling a function calleddisplayTotal()which we don't see here. Maybe you just used the wrong function reference?$(this).val()thanthis.val()- notethisin callback is pureHTMLElementnotjQueryitems set.$(this).val()which is short hand for$(this).attr('value')ie exactlythis.valuethisinside the callback references the element itself, it doesn't create a new jQuery object for each element.