I found this solution for my problem but I need some additional help:
How to use jQuery to add form elements dynamically
I have a form (here I'll copy a short version), and it is used for entering some tasks by users. Users can enter as many tasks as they like in period of 2 years. The script is working correctly, but I have a problem with counter of element IDs. Probably it can be solved with slight modification of javascript.
So here is html:
<div class="extraNew">
<div class="row">
<label>Task:</label>
<textarea class="span3" placeholder="Task" type="text" name="task"></textarea>
<label>Description:</label>
<textarea class="span3" placeholder="Description" type="text" name="description"></textarea>
</div>
</div>
<div id="container"></div>
<div class="row">
<a href="#" id="addRow" class="addRow">Add row</p></a>
</div>
And here is javascript
<script type='text/javascript'>//<![CDATA[
$(function(){
$(document).ready(function () {
$('<div/>', {
'class' : 'extra', html: GetHtml()
}).appendTo('#container');
$('#addRow').click(function () {
$('<div/>', {
'class' : 'extra', html: GetHtml()
}).hide().appendTo('#container').slideDown('slow');
});
});
function GetHtml()
{
var len = $('.extra').length;
var $html = $('.extraNew').clone();
$html.find('[name=task]')[0].name="task" + len;
$html.find('[name=description]')[0].name="description" + len;
return $html.html();
}
});//]]>
</script>
But POST results I get afterwards are not so good:
Array (
[task] => blah
[description] => blah
[task0] => blah
[description0] => blah
[task1] => blah
[description1] => blah ... )
And If I fill this form only once, without adding new row I get this result:
Array
(
[task] => blah
[description] => blah
[task0] =>
[description0] =>
)
This ZERO bothers me. It always resets the counter to 0, and I'm afraid of unwanted problems when users will want to change something in the future. I need to give users an option to change or delete some task. I'm afraid that these actions will make a mess in MySQL.
I would like to add ID 1 (or zero) to the first set of form elements, and set counter from last set of elements (so if only 1 set is entered, the next set will have ID 2 ofcourse). And afterwards I will collect all POST data and store it in MySQL with FOR loop without worrying of ID order.
And with the same method I will output the data via PHP. So probably, I will first create initial form with PHP and query from MySQL - If some rows already exists in MySQL, display them and set counter incrementally; and if returns 0 rows, display elements starting from 1 (or zero).
I hope I explained everything correctly. So to repeat the question: How to change jquery to create element IDs incrementally and always making sure that new element ID is +1 from last element ID?