0

I am trying to get the total value from an array of form fields but for some reason the value is incorrect on Keyup the final value gets added from the last inputed value and not all of the fields here is my function:

function percentage_hardcoded_form(_formharcoded_id, _form_fieldArray, _form_hardcodedtotalWrapper, _form_hardcodedtotalId) {

            var _form           = $j(_formharcoded_id);
            var _sumDisplay     = _form.find(_form_hardcodedtotalId);

            $j(_form_hardcodedtotalId).attr('disabled','disabled');


            $j.each(_form_fieldArray, function(index, item) {

                var _summands       = item;
                var sum             = 0;

                _form.delegate(_summands, 'change', function () {

                    //$j.each(function () {    
                        var value = Number($j(this).val());
                        if (!isNaN(value) && !$j(this).is(_form_hardcodedtotalId)) sum += value;
                    //});

                    if(sum === 100)
                    {
                        // is 100 
                        $j(_form_hardcodedtotalWrapper).removeClass('warning');
                        $j(_form_hardcodedtotalWrapper).find('.QuestionWarning').hide();
                    }
                    else
                    {
                        // isnt 100
                        $j(_form_hardcodedtotalWrapper).addClass('warning');
                        $j(_form_hardcodedtotalWrapper).find('.QuestionWarning').show();
                    }

                    _sumDisplay.val(sum);

                });
            });
        }

        percentage_hardcoded_form('#aspnetForm #questions_page_Page17', designForm_ids_1, "#question_DCWorkSplit", "#DCWorkSplit");

Here is a jsfiddle of what I am working with: http://jsfiddle.net/q05k48b7/1/

Update

I have updated the JS fiddle see link below, still not working.

http://jsfiddle.net/q05k48b7/2/

4
  • Your sum always resets to 0 on every onblur event. Commented Jul 1, 2015 at 6:34
  • Ok I tried putting the var sum outside of the each but it keeps on adding to the total but doesn't remove when a value is decreased? Any ideas? Commented Jul 1, 2015 at 7:51
  • If I would do it, I will assign a common class to that group of textbox, and get the values of each textbox (through the class), sum them up, and assign to another textbox, every time an onchange event happens Commented Jul 1, 2015 at 8:09
  • Unfortunately I cannot modify the html in my clients system this is why I am using ids. I am not sure why the sum is not calculating each value just adding to the total? Commented Jul 1, 2015 at 8:24

1 Answer 1

1

How about simplifying the code by introducing a Form-type object, for each of the different forms you have?

var formObj = function($){
    var fields = [];
    var total = 0;
    var totalField = null;

    return {
        setFields: function(fieldIds){
            fields = fieldIds;
        },
        setTotalField: function(fieldId){
            totalField = fieldId
        },
        setTotal: function(){
            var total = 0;
            $.each(fields, function(idx,item){
                var v = $('#'+item).val();
                if(!isNaN(v)){
                    var nV = Number(v);
                    total += nV;
                }
            });
            $('#'+totalField).val(total);
        };
    };
};

You could then use it like this:

var form1 = new formObj($j);
form1.setFields([
    'TurnoverFromOwnDesign',
    'Feesinrespectofdesignonly',
    'TurnoverFromSubcontractedWork',
    'TurnoverFromSupervisedWork',
    'TurnoverDesignsByClient',
    'DCAllotherturnover'
]);
form1.setTotalField('DCWorkSplit');
form1.setTotal();

The question isn't too clear - an MVCE would help, but I think this fiddle demonstrates the above pattern doing what you're trying to.

Note that the fiddle calls the setTotal method for each formObj on the input change handler:

$j('#questions_page_Page17 input').change(function(){
    form1.setTotal();
    form2.setTotal();
});
Sign up to request clarification or add additional context in comments.

3 Comments

That looks a much better way of doing it, I will test when I get back to my desk, thank you so much this was driving me crazy.
@neo No problem, hope it works out! Let me know if you run in to difficulty.
All works great, I actually fixed my original question by adding a separate function outside of the original function and called it inside of the each. But I have used your version as it works better. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.