#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2001
    Posts
    130
    Rep Power
    14

    Dynamic number of Form Elements between PHP and Javascript


    Hi all,
    I'm doing a shopping cart using PHP and Javascript (and mySQL) and I need a little help. I want to be able to provide a list of the items in the shopping cart that allows you to change the Quantity. When you exit the quantity box for the item, all the totals are updated. The problem is, becuase I am building the Javascript dynamicly at runtime depending on the number of items in the cart, I am using a number variable (QTY1, QTY2, etc.)
    I can build this with PHP. Then, after finishing the changes, the user can clik checkout or return to shopping. Either way, I have a PHP script run throught the cart and update the quantities based on the users input. PHP won't let me do QTY$number and Javascript won't let me QTY[$number] how do I do this?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2001
    Location
    The Netherlands
    Posts
    200
    Rep Power
    14
    Not sure if this is what you need, but you can do:

    for(iterator=0; iterator<nr_of_items; iterator++)
    {
    // retrieve quantity
    qty = eval("document.myForm.qty"+iterator+".value");
    // calculate total cost for this qty field
    cost = qty * eval("document.myForm.price"+iterator+".value");


    There are other ways to address form elements.

    Loop through document.myForm.elements for instance.

    But eval is easier.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2001
    Posts
    130
    Rep Power
    14

    The solution was variable variables!


    I stumbled on an article here about variable variables and it was the solution. For instance, to access QTY1, QTY2, QTY3, etc. My code was:
    $sql = "select * from ShoppingCartItems where CartID = '$id'";
    $result = mysql_query($sql);
    $number = 1;
    while ($myrow = mysql_fetch_array($result)) {
    $ProductID = $myrow['ProductID'];
    $varname = "QTY$number";
    $Quantity = ${$varname};
    $newsql = "update ShoppingCartItems set Quantity = '$Quantity' where CartID = '$id' and ProductID = '$ProductID'";
    $newresult = mysql_query($newsql);
    $number++;
    }

    The two lines that do the work are $varname = "QTY$number";
    which produces a string ($varname) which holds "QTY1", "QTY2", etc in order. The second line is $Quantity = ${$varname}; which get interpreted into
    $Quantity = $QTY1;
    $Quantity = $QTY2;
    etc. in sequence. The string "QTY1" is turned into the variable $QTY1 by the curly braces.

IMN logo majestic logo threadwatch logo seochat tools logo