I am creating a form where a user can input certain information. The default state looks as following;
<div class="options">
<input type="text" name="option[]" />
<input type="text" name="content[]" />
</div>
Now, by clicking a button ADD, I will add two new fields with the same name so the state is as follows;
<div class="options">
<input type="text" name="option[]" />
<input type="text" name="content[]" />
<input type="text" name="option[]" />
<input type="text" name="content[]" />
</div>
Then, I want PHP to eventually create a string as below;
valueOfFirstOption:valueOfFirstContent,valueOfSecondOption:valueOfSecondContent
And so on, and so on. Theoretically I should be able to add an infinite amount of input fields.
Is this possible what I am trying to achieve? Or should I be adding unique names to the input fields?
Any tips or hints how I should be going? Or somebody got a tutorial/example code for me?
Thanks in advance.
This would be a bit nicer if you could set indexes in the name when you add the extra elements.
<div class="options">
<input type="text" name="data[0][option]" />
<input type="text" name="data[0][content]" />
<input type="text" name="data[1][option]" />
<input type="text" name="data[1][content]" />
</div>
<a href="#" onclick="addSet(); return false;">Add</a>
<script>
var addSet = function() {
var container = document.getElementsByClassName('options')[0];
var numInputs = container.getElementsByTagName('input');
var numSets = numInputs/2;
var nextIndex = numSets;
var newOption = document.createElement('input');
newOption.name = 'data[' + nextIndex + '][option]';
container.appendChild(newOption);
var newContent = document.createElement('input');
newContent.name = 'data[' + nextIndex + '][content]';
container.appendChild(newContent);
}
</script>
Then when you receive the POST, you can just loop through data and process the duplets
$pieces = array();
foreach ($_POST['data'] as $set)
$pieces = $set['option'] . ':' . $set['content'];
}
// or
for ($i = 0; $i < count($_POST['data']); $i++) {
$pieces[] = $_POST['data'][$i]['option'] . ':' . $_POST['data'][$i]['content'];
}
// then
$compiledString = implode(",", $pieces);