wickywills
wickywills

Reputation: 4204

Adding up values of multiple inputs

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);

JSFiddle

Upvotes: 0

Views: 218

Answers (2)

Eternal1
Eternal1

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:

  1. It includes validation method validateInput, that replaces any non-numbers, and return 0 if value is empty;
  2. It doesn't require 'dirty checking' every time interval to determine if value has changed, so it is more efficient;
  3. It is reusable - if you need to calculate some other values elsewhere - you can easily do so just by passing an object containing different selectors, methods, and whatever, and it would still work just fine, and you'd need to simply call $("#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

Selvaraj M A
Selvaraj M A

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

Related Questions