I have unknown number of input fields, having class "add" I just wants to sum these with jquery, dont know where I am wrong.
<input name="add" class="add" type="text">
<input name="add" class="add" type="text">
<input name="add" class="add" type="text">
<input name="add" class="add" type="text">
<input type="button" value="" onClick="add()" />
`
function add(){
val = 0;
$(".add").each(function() {
str = (parseInt(this.value))
sum=str+str
});
alert (sum)
}
`
You're never actually adding stuff into sum
:
function add() {
var sum = 0;
$(".add").each(function() {
sum += +this.value;
});
return sum; // an add function shouldn't really "alert"
}
If the intention is to only support whole numbers, use parseInt(this.value, 10)
[note the radix parameter] instead of +this.value
:
function add() {
var sum = 0;
$(".add").each(function() {
var str = this.value.trim(); // .trim() may need a shim
if (str) { // don't send blank values to `parseInt`
sum += parseInt(str, 10);
}
});
return sum;
}
See http://jsfiddle.net/alnitak/eHsJP/
function add(){
var sum = 0;
$(".add").each(function() {
var val = parseInt($(this).val(), 10)
sum += (!isNaN(val) ? val : 0);
});
alert(sum);
}
Edit: Sharp eyes, got the parenthesis... =) And the space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With