1

The script below is throwing an error (customfields is not defined). Do I need to pass the element IDs differently?

I'm trying to seed the array with the form fields that I'm looking to calculate. It should iterate through each of the form fields in the array and increment the sum variable with the value of the form element.

jQuery(document).ready(function(){

    jQuery("#customfield_21070").attr('style','width:60px');
    jQuery("#customfield_21070").attr('disabled','disabled');

    var customfields = [
    '#customfield_11070',
    '#customfield_11071',
    '#customfield_20071',
    '#customfield_20072',   
    '#customfield_20073',
    '#customfield_20074'
    ];

    jQuery(customfields).each(function() {
        jQuery(this).attr('style','width:60px');

            jQuery(this).keyup(function(){
                calculateSum();
            });


        });

    });

    function calculateSum() {

        var sum = 0;

        //iterate through each textboxes and add the values
        jQuery(customfields).each(function() {

            //add only if the value is number
            if(!isNaN(this.value) && this.value.length!=0 && this.id !== "customfield_21070") {
                sum += parseFloat(this.value);
            }

        });
        //.toFixed() method will roundoff the final sum to 2 decimal places
        jQuery("#customfield_21070").val(sum.toFixed(2));
    }
0

3 Answers 3

0

jQuery's .each() method is meant to iterate over a jQuery object. You should use a simple for loop to iterate your array – it's a lot faster than using the jQuery .each() method, anyway.

for(var i=0, len=customfields.length; i<len; i++) {
    console.log(customfields[i]);
}

Proof about performance claims: http://jsperf.com/jquery-each-vs-for-loop

Sign up to request clarification or add additional context in comments.

1 Comment

I think your answer makes sense. Console.log is working. Now i just need to get the calculate function to work > stackoverflow.com/questions/16091742/…
0

Try this using the jQuery.each()

$.each(customfields, function (index, value) {
    $(value).attr('style', 'width:60px');  // OR $(value).width(60);
    $(value).keyup(function () {
        calculateSum();
    });
});

Comments

0

Passing an array to jQuery is not going to use the entries in the array as selectors. You have to pass the selector as a string. When you call this.value the this is actually a string and not an element. Try

jQuery(customfields.join(','))

2 Comments

However, it will treat it as an array of strings, he is then selecting them inside the each properly.
@KevinB in the first .each which I believe is a coincidence, but not in the second one.

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.