Dynamically create and repeat the set of fields
I have a PHP form which shows one 'User details' block by default. 'User detail开发者_StackOverflow中文版s' section has first name, last name and address etc. I have a requirement to repeat the same block after clicking on the button so the user can enter 'n' number of users into on the form. Also I need to save all the information in MySQL database. What is the best way to achieve this? Please let me know. I appreciate any help.
Thank you.
I would use jQuery to add additional form elements. You'll need to give each element a different 'name' attribute though- I'd use something like name='user1name' (and in the next username field name='user2name'). Comment on my post if you need specific help with that. When the form submits, I'd use php to loop through each set of fields with an insert statement at the end of the loop.
PHP is something like this:
for ($i = 1; is_null($_POST['name' . $i]) == false; $i++) {
$name = $_POST['user' . $i . 'name'];
// repeat for all your fields
// do your insert statement here - 1 insert per user created
mysql_query("INSERT INTO table_name (Name, Address, ...) VALUES ('$name', '$address', ...)");
}
jQuery is something like this:
Existing HTML Should only have 1 div with class=user at this point
<div id='fields'>
<div class='user'>
<input type='text' name='user1name' />
<input type='text' name='user2name' />
... more elements ...
</div>
</div>
jQuery
var userFields = $("div.user").clone();
$(userFields).appendTo("div#fields");
$("div#fields").children("div.user:last").children().each(function() {
// change names here!
});
This will copy the existing field and add its copy to the fields div. It will also set the new names for the second set of user fields. Note: you only need ot set userFields once, and then you can use $(userFields).appendTo("div#fields");
as many times as you need to (as long as the userFields variable is in scope).
If you have event handlers attached to your elements in the user field, use $("div.user").clone(true, true);
instead of $("div.user").clone();
.
精彩评论