JQuery: union through input elements

I have lines of input fields (text) that I need to iterate over, multiplying the values ​​in the line and then summing the products. The only solution I could find was to convert input fields to arrays:

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

And then repeat and summarize 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; } } 

It works. However, I am just learning jQuery and want to use the canonical method.

+4
source share
3 answers

you can scroll through all the elements found with the selector as follows:

 $('input').each(function(index,data) { var value = $(this).val(); }); 
+7
source

As already mentioned, you can use .each () to accomplish this task, but here is an example that uses your data on demand in the question. You mentioned input "rows", so I assume this is in the table row:

 $('tr').each(function () { var $this = $(this), sum = parseFloat($this.find('input[id$="txtVal1"]').val()) * parseFloat($this.find('input[id$="txtVal2"]').val()); alert(sum); }); 

Here's an example jsFiddle

+1
source

No need to use toArray , use . each () .

 $('input[id$="txtVal1"]').each(function(index) { // do something here $(this).addClass( "myClass" ); }) 
0
source

All Articles