I'm chasing a bit of a challenge handling an HTML form whose input fields are created dynamically using JavaScript DOM containing multiple select fields as well. Here is a sample code of the form I have:
<input type="text" name="attributeIndex[]" id="brand" class="form-control" placeholder="brand">
<select name="attributeIndex[]" id="color" class="form-control">
<option value="92">Aero</option>
<option value="277">Aluminum</option>
<option value="91">Amber</option>
</select>
After submitting the form, I want to get the form data in a PHP array like this:
$formData=$_GET['attributeIndex'];
The array $formData should be like this:
array(
[0]=>text input value here
[1]=>array(list of selected colors here)
)
Any suggestion will be highly appreciated!
Name the select with an additional []
:
<select name="attributeIndex[][]"
That way each value PHP puts into $_GET
will be in an array in an array.
You'll also need to add the multiple
attribute if you want more than one option to be selected.
<select name="attributeIndex[][]" multiple id="color" class="form-control">
<form action="#" method="post"><input type="text" name="attributeIndex['brand'][]" id="brand" class="form-control" placeholder="brand">
<select name="attributeIndex['color'][]" id="color" class="form-control" multiple="multiple">
<option value="92">Aero</option>
<option value="277">Aluminum</option>
<option value="91">Amber</option>
</select>
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['submit'])) {
print_r($_POST['attributeIndex']);
}
?>
You can try above this. By using attributeIndex['brand'] you can get dynamic brand names and attributeIndex['color'] you can get dynamic color names.