Tie two inputs together (text & hidden)?

后端 未结 3 739
天命终不由人
天命终不由人 2021-01-25 07:04

I have a loop below that is showing a quantity box and includes a hidden field containing the product name.

I want these to be tied together so if out of 100 inputs the

相关标签:
3条回答
  • 2021-01-25 07:36

    I recommend using the product ID in the quantity array like this:

    <input type="text" name="quantity[<?php the_title(); ?>][]" value="0"> 
    

    Ofc, this is not the answer you were looking for, but an alternate version which should also work.

    0 讨论(0)
  • 2021-01-25 07:45

    You obviously need to iterate over both arrays in tandem so that you can see if a product's quantity is nonzero in order to decide if it should be displayed.

    In general foreach is an awkward tool for this job, and the way to go is with a for loop and indexing into both arrays using the same counter. However, in this specific case you can easily transform your two arrays into one where the keys are product names and the quantities are the values using array_combine:

    $quantities = array_combine($_POST['product'], $_POST['quantity']);
    

    You can then easily iterate with foreach:

    foreach ($quantities as $product => $quantity) {
        if ($quantity > 0) {
            echo "$quantity x $product<br>";
        }
    }
    
    0 讨论(0)
  • 2021-01-25 07:50

    Rob, I see you have a good answer but you might like to be aware of a significant issue.

    By posting independent quantities[] and products[], then you are relying on the two serializations being conformal with each other - ie. that both are serialized in DOM order - hence that the indexes of $_POST['quantity'] and $_POST['product'] correspond element-by-element. For me, this is not a completely safe assumption - see the selected answer here.

    It would be far safer, and more conventional, to have one <input> field per product, named with a representation of product-id and a value representing quantity. Thus, product-ids and their values are guaranteed to correspond.

    Client-side and server-side code would need to be reviewed accordingly.

    0 讨论(0)
提交回复
热议问题