Tania Rascia Tania Rascia - 2 years ago 82
jQuery Question

Sending Duplicate Name Values in a PHP Form

I'm sure I'm going about this the wrong way, so I'm here to ask.

I have a form that's sending out multiple HTML form

keys (
attribute) and values (

The looks HTML like this:

<input type="text" value="0" name="Quantity">

I have some jQuery multiplying price by quantity and submitting them to the form.

Here is a link to a pen demonstrating the form.

That part works fine. Then on form submit, I'm just serializing all the data and sending it through with
. Simplified example...

$('form').on('submit', function (event) {

var formValues = $(this).serialize();
type: 'POST',
url: 'send.php',
data: formValues

And the PHP looks like this (simplified!)

foreach ($_POST as $key => $value) {
$message .= $key.': '.$value. "\n";

So, everything works properly - the JavaScript adds up all the quantities and sends it to the PHP. My only issue is you can't have multiple
attributes sending out, so I have to change them for each input.

<input type="text" value="0" name="Quantity1">
<input type="text" value="0" name="Quantity2">

So, I guess my question is how to change the name attribute to something more readable in an e-mail.

In other words, the e-mail sends out as:

  • Product 1

  • Quantity1: 10

  • Product 2

  • Quantity2: 12

and I want it to just be...

  • Product 1

  • Quantity: 10

  • Product 2

  • Quantity: 12

Answer Source

For all your inputs you can do <input type="text" value="0" name="quantity[]"> and in your php

foreach($_POST['quantity'] as $quantity){
 .... your stuff here

Seems like your products and quantities are in order and the same length i.e for every product there is only one quantity field. If that's true you can iterate through both in one loop.

$quantities = $_POST['quantity'];  // array of quantities

$products = $_POST['products'];  // array of products

for ($i = 0; $i < count($_POST['quantity']); $i++){

     $quantity = $quantities[$i]; 
     $product = $products[$i]; 

 .... do more stuff here 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download