I’m developing a registration website and there’s a part where I need to add people. What I do is when they click on a text bellow the name and last name of the person another two fields (asking the name and the person once again, so it’s a copy of the one above) appear. This I do it using the clone() method. So let’s say the name and last name are inside a div with a class called: “information”. And the <p> that adds the extra div when contained has an id called: “add”. Like this:
<div class="information">
<label for="name">Name</label>
<input type="text" name="name[]"> //it's an array because there's gonna be probably more than one (if they click the "add" text)
<label for="last_name">Last Name</label>
<input type="text" name="last_name[]">
</div>
<p id="add">Add another person</p>
My javascript (jquery) is the following:
$('#add').click(function(){
$('.information').clone().insertAfter('.information');
});
The problem with this is that when you click the add text it copies the first div (and if you wrote something on it, it copies it too). So how can I solve that. Is there any other way to do it? Plus, is there any easy way to make a button to disappear an “information” div (in case the user regrets how many people he wants to add).
Any recommendation is well received.
Thanks in advance.
EDIT:
Sorry guys. There’s something important that I forgot to say. The information class is only displayed if the user click a checkbox (because there’s the possibility that they don’t wish to add any other person.
So, here is the code for the checkbox:
HTML (above the information class):
<input type="checkbox" id="companion" />Companion
JQuery:
$("#companion").click(function() {
$(".information").toggle();
if ($('#companion').is(":checked")) {
$('#add').show();
}
else {
$('.companion').hide();
$('.companion').removeAttr('checked');
}
});
I clarify this because I tried the examples that you guys show me but when I click the checkbox the information div does not show up.
I should have mention this on my original post. I really sorry.
I’d change it just slightly and do it like this jsFiddle example.
This allows you to add people and remove any new one you add while always leaving just the first person.
HTML
jQuery