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));
    }
Adam Szabo
  • 11,302
  • 18
  • 64
  • 100
js-newb
  • 421
  • 6
  • 16

3 Answers3

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(','))
Musa
  • 96,336
  • 17
  • 118
  • 137
  • However, it will treat it as an array of strings, he is then selecting them inside the each properly. – Kevin B Apr 18 '13 at 18:53
  • @KevinB in the first .each which I believe is a coincidence, but not in the second one. – Musa Apr 18 '13 at 19:26
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

ryanbrill
  • 1,981
  • 10
  • 13
  • I think your answer makes sense. Console.log is working. Now i just need to get the calculate function to work > http://stackoverflow.com/questions/16091742/jquery-passing-array-values-into-a-function – js-newb Apr 18 '13 at 19:44
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();
    });
});
palaѕн
  • 72,112
  • 17
  • 116
  • 136