I needed a form that allows the user to add and remove products with quantities as he wishes.
The form had one row with a product and quantity inputs that I decided to clone each time, change the id to an incremented id, remove the value from the field and update the input names.
This is what I did:
1 2 3 4 5 6 7 8 9 10 11 12 |
Head Section: <script language="JavaScript"> iprdct=1; </script> Using the onClick event (messy, should be done in a ready function): <table id="quotes" width="100%"> <tr><td valign="top" style="font-size: 15px;" class="text"><strong>Products</strong></td><td valign="top" style="font-size: 15px;" class="text"><strong>Quantity</strong></td><td></td></tr> <tr id='quoteTr1'><td valign="top" style="font-size: 15px;" width="240" class="text"><input name="prdctQ1" id="prdctName" type="text" value="<?=$prdctS?>"><br/><a style="font-size:14px;" href="#" tabindex="500" onClick="iprdct++;$(this).parent().parent().clone().appendTo('#quotes').attr('id','quoteTr'+iprdct);$( '#quoteTr'+iprdct).find('#prdctName').attr('name','prdctQ'+iprdct).val('');$( '#quoteTr'+iprdct).find('#prdctQuant').attr('name','quantQ'+iprdct);$('#nmbrPr').val(iprdct);return false;">+Add</a><a href="#" style="font-size:14px;" tabindex="501" onClick="if ($( '[id^=quoteTr]' ).length > 1) $(this).parent().parent().remove();"> -Remove</a></td><td valign="top" style="font-size: 15px;" class="text"><input name="quantQ1" id="prdctQuant" style="width:40px;" onkeypress='return event.charCode >= 48 && event.charCode <= 57' type="text" value="1"></td><td></td></tr> </table> |
I added the increment variable’s value to a hidden field so I could retrieve him in the processing script:
1 |
<input type="hidden" name="nmbrPr" id="nmbrPr" value="1"> |
The processing file used the following code:
1 2 3 4 5 6 |
$loopy = htmlspecialchars($nmbrPr); for ($x = 1; $x <= $loopy; $x++) { if (${'prdctQ'.$x} !='') { $Body .= "<tr><td>".${'quantQ'.$x}." ".${'prdctQ'.$x}."</td></tr>\n\n"; } } |