jonny b
jonny b

Reputation: 75

How can i use a HTML form to POST dymanic options to a php script?

I have a HTML form where a user can add a new row and select a menu item, the number of rows they can add is unlimited, however each dropdown menu on the new added row is the same.

The example below allows a user to select an animal, then a number. The form is dynamic so they can select as many differnt animals and enter a number for each animal.

HTML:

<select id="option" name="option[]" class="green-field form-control">
        <tr>
        <option value="1">bear</option>
        <option value="2">beaver</option>
        <option value="3">dog</option>
        <option value="4">kangaroo</option>
        <option value="5">cow</option>
</tr>
<input class="green-field form-control number" id="number" placeholder="Enter Number of animals" name="number[]">

When the form is submitted a POST request is sent with data like the following:

option[]=1&number[]=2&option[]=2&number[]=55&option5[]=4

The actual menu consists of over 100 options, and depending on number of items added by the user, each option may or not be selected, so i am unsure how to dynamically capture the posted variable with PHP.

The form is then posted to submit.php I want to echo the submitted values, i have tried the normal way such as the following:

<?php
$name = $_POST['option[]'];
$number = $_POST['number[]'];

echo $name;
echo $number;

?>

This does not catch the submitted data so it does not echo, I think the PHP may need to loop through all Options and create variables for all options that are posted, and then echo them so the result would be:

1 = 2
2 = 55
5 = 4

How can i acheive this?

Upvotes: 0

Views: 24

Answers (1)

pavel
pavel

Reputation: 27082

Use foreach loop to iterate both arrays.

foreach ($_POST['option'] as $key => $opt) {
    echo $_POST['name'][$key] . ': ' . $opt . '<BR>';
}

Upvotes: 1

Related Questions