Reputation: 537
I have a form that adds a new user into the database. It all works perfectly, but what I want is to be able to add more than one user at a time, so when I click to "Add another user", it would appear another list of fields for adding a user. I don't know exactly how to explain it so I'll add some pictures:
Here is what I have when I try to add a user:
And, what I want is that when I click on "Add another user", to show me another list of fields under the other, like this:
So, if I click five times, it would show me five "forms" and the original one:
I've found this question where it shows how to do it with a different example, but my code has a table and a form so I don't know much exactly how to do it. Here's my form code:
<table id="minimalist-table">
<tr><th>Username</th><th>Password</th><th>Mail</th><th>Language</th><th>Sex</th></tr>
<form method="post" action="?action=users&sa=add">
<tr>
<td><input type="text" name="username[]" required="required"></td>
<td><input type="password" name="password[]" required="required"></td>
<td><input type="email" name="email[]" required="required"></td>
<td><select name="language[]">
<option value="en_US">English</option>
<option value="es_ES">Spanish</option>
</select></td>
<td><select name="sex[]">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select></td>
</tr>
<tr><td><input type="submit" value="Submit"> </td></tr>
</form></table>
I have the values with arrays (like name="email[]"
) because it's the way I can handle multiple elements for the database...
I've tried to put all this code into a function, so when I call the function it adds another group of fields into the form, but I don't know how to do it with JavaScript...
Thanks!
Upvotes: 0
Views: 397
Reputation: 8849
In such cases I usually create a hidden "template" element/row containing the HTML that should be added:
<table id="minimalist-table">
...
<tr class="template" style="display:none">
... all fields ...
</tr>
<tr class="submit_row"><td><input type="submit" value="Submit"> </td></tr>
So in the javascript you can do this to get the HTML (and disable the hidden inputs):
var row_template = $('#minimalist-table > .template').html().find(':input').prop('disabled', true)
The finished code would look something like this (untested)
var row_template = $('#minimalist-table > .template').html()
$('#add_row').on('click', function(){
$('#minimalist-table .submit_row').before(row_template);
});
Upvotes: 1