Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Looping through input elements

Tags:

jquery

loops

I have rows of input boxes (text) that I need to iterate over, multiplying values within a row and then summing the products. The only solution I could find is to convert the input boxes to arrays:

var array1 = $('input[id$="txtVal1"]').toArray();
var array2 = $('input[id$="txtVal2"]').toArray();
var temp1;
var temp2;
var sum=0;

And then iterate and sum using:

for (i = 0; i < array1.length; i++) {
    if (array1[i].value.length > 0) { //make sure we have data
        temp1 = parseFloat(array1[i].value);
        temp2 = parseFloat(array2[i].value);
        sum += temp1 * temp2;
    }
}

This works. However I'm just learning JQuery and want to use the canonical method.

like image 782
user2216179 Avatar asked Mar 27 '13 15:03

user2216179


1 Answers

you can loop directly over all the items found through a selector like this:

$('input').each(function(index,data) {
   var value = $(this).val();
});
like image 108
Gung Foo Avatar answered Oct 11 '22 23:10

Gung Foo