Link to home
Start Free TrialLog in
Avatar of Westside2004
Westside2004Flag for United States of America

asked on

Javascript Looping over multiple forms

Hi,

I have this query that I am looping over.  It basically contains multiple products that I display on a page for an e-commerce site.  Each product has a quantity that the user can specifiy in a basic input box and each product has a price obviously.   I want to have a js function that will basically grab the value in that 'qty' text box, multiple it by the price for that product and give me the total.  Since there *could* be multiple products, I want to ensure the grand total at the end is a sum of each indiviudual products' total if that makes sense.  So product "A", lets say has a qty of 2 and a price of $5.00.  The total for cost for product "A", is $10.00.  So if there was another product the user wanted to get, product "B", qty of 3, price of $2.00, the total would be $6.00.  The grand total then for product "A" and product "B" is $16.00.  I want to ultimately display this at the end.  The problem seems to be around uniquely identifying each html 'qty' input field, do I append a counter or how can this be done???

It would be nice to be able to display total next to each product, and then a grand total at the bottom ideally.

My HTML:

<table width="500" border="0">
 <tr>
    <td>Quantity:</td>
    <td><input type="text" id="qty" name="qty" size="3" maxlength="3" value="" onBlur="calculateProduct();"/></td>
 </tr>
</table>

Javascript:
function calculateProduct() {
  // loop over each form ???
  for (i=1;i<document.forms.length; i++ {
   
  }
}

Thanks,

-ws

Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Thoughts:

1) Set an ID for the table:

   <table id="table1" width="500" border="0">

2) Add a total column.

3) Get a reference to the table by id:

   var table = document.getElementById('table1');

4) Loop through the rows and get the cells:

  for (var i = 0; i < table.rows.length; i++)
  {
     var qty = table.rows[i].getElementById('qty');
  }

Bob
ASKER CERTIFIED SOLUTION
Avatar of gops1
gops1
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Westside2004

ASKER

Yes, that works.  Works fine for me.

Thank you.

Appreciated

-ws