I am developing the app using CakePHP 1.3 Now I want to make the "Insert function" to add new user into database. I have 2 fields user & pass to insert. But I not only insert 1 user, I want insert one or multiple user (optional). If I want to add more user I will click to "add more" to add new field in view.
In cakephp, it required when we want to insert a array with multiple data. The field name will be define as:
<?php
echo $this->Form->input('Modelname.0.fieldname');
echo $this->Form->input('Modelname.1.fieldname');
?>
and in view will be:
<input type="text" id="Modelname0Fieldname" name="**data[Modelname][0][fieldname]**">
<input type="text" id="Modelname1Fieldname" name="**data[Modelname][1][fieldname]**">
My question is: Does JQuery have some function to add new element and how can I increase the index number follow the pattern above data[Modelname][0][fieldname]
Thank for your view and suggestion.
I've created this code, here it is, I've tested it and it works
http://codepen.io/anon/pen/xbxVQG
some important notes:
1- The div who's
id="insertBefore"
is just to tell jQuery where to put the new duplicated fields.2- The jQuery code works with an index variable (
$i
) that starts in 0 and gets incremented by 1 on each new click on the "+" button (so the first time you click, it should get to 1)3- The original Form's code (where value is 0 by default) is printed everytime the + button is clicked, but replacing each
0
in the html code by'+$i+'
3.2 - If you make some changes to the code of your form, by this method, you should change the javascript code as well. I know it's not an elegant solution to do this, but it shouldn't be so difficult either, just remember to copy the exact html code, delete all
intro
's and replace all0
's with'+$i+'
4- The "Index N." div is just keeping track of the user's number, you could put your own text there, like "User Nº 0" and in the jQuery code replace the 0 with the value of
$i
5- You could put a limit to the number of users (example:10) that can be added by creating an
if($i<10){}
variable inside the.click()
function