Reputation: 4204
I am trying to get the value from a bunch of input text fields on a form, then check whether or not they add up to 100. I am using the below jQuery to do this, though I just get "NaN" returned - anyone know why this is? No Doubt something stupid I've missed(!)
var formPercentageTotal = 0;
var currentVal = 0;
setInterval(function(){
$('.percentage-validate input.three-digit').each(function(){
currentVal = $(this).val();
currentVal = parseInt(currentVal);
formPercentageTotal = formPercentageTotal + currentVal;
});
$('.percentage-validate .percentage-current').text(currentVal);
}, 500);
Upvotes: 0
Views: 218
Reputation: 5625
The question is already answered, but there are some things about your code, that make it inefficient and quite error-prone. Consider this piece of code:
$.fn.boundForm = function(options) {
var defaults = {
fields: ".three-digit",
total: ".percentage-current",
validateInput: function(item) {
item.value = parseInt(item.value.replace(/[^0-9]+/g, "")) || 0;
return parseInt(item.value);
},
calculateTotal: function(fields) {
return fields.toArray().reduce(function(sum, item) {
return sum + this.validateInput(item);
}.bind(this), 0);
},
refresh: function(form) {
form.find(this.total).text(this.calculateTotal(form.find(this.fields)));
}
}
var o = $.extend({}, defaults, options);
this.each(function() {
var $form = $(this);
$form.on("input", o.fields, function() {
o.refresh($form);
});
o.refresh($form);
});
};
$(".percentage-validate").boundForm();
This is a basic widget, that does the same thing as your code, but:
validateInput
, that replaces any non-numbers, and return 0 if value is empty;$("#myContainer").boundForm(myOptions)
;All in all, that makes for much more convenient code to work with. Hope that helps.
P. S. Here's fiddle
Upvotes: 1
Reputation: 3136
Try checking for NaN before adding up. You might have entered a alpahabet in any of the input field. Fiddle
Edit: You should set formPercentageTotal into .formPercentageTotal
.
var formPercentageTotal = 0;
var currentVal = 0;
setInterval(function(){
$('.percentage-validate input.three-digit').each(function(){
currentVal = $(this).val();
currentVal = parseInt(currentVal);
if (!isNaN(currentVal)) {
formPercentageTotal = formPercentageTotal + currentVal;
}
});
$('.percentage-validate .percentage-current').text(formPercentageTotal);
}, 500);
Upvotes: 3