javascript - jQuery seed each() with an array of elements -
the script below throwing error (customfields not defined). need pass element ids differently?
i'm trying seed array form fields i'm looking calculate. should iterate through each of form fields in array , increment sum variable value of 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 , add values jquery(customfields).each(function() { //add if value number if(!isnan(this.value) && this.value.length!=0 && this.id !== "customfield_21070") { sum += parsefloat(this.value); } }); //.tofixed() method roundoff final sum 2 decimal places jquery("#customfield_21070").val(sum.tofixed(2)); }
jquery's .each() method meant iterate on jquery object. should use simple for loop iterate array – it's lot faster using jquery .each() method, anyway.
for(var i=0, len=customfields.length; i<len; i++) { console.log(customfields[i]); } proof performance claims: http://jsperf.com/jquery-each-vs-for-loop
Comments
Post a Comment