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
If it’s numbers you’re adding then this should work:
DEMO
If you want this to work on page load then add a call to
addAllin the.ready()function. Here’s the full code: