I'm building a form where I need multiple optional inputs, what I have is basically this:
Every time a user presses the plus button a new row of form inputs should be added to the form, how can I do this in jQuery? Also, is it possible to automatically add a new row when all rows (or just the last row, if it's easier / faster) are filled? That way the user wouldn't need to press the plus button.
I'm sorry for asking maybe such a basic question but I'm still very green with jQuery, I could do this with PHP but I'm sure Javascript / jQuery plays a more appropriate role here.
Thanks in advance!
@alex:
<!DOCTYPE html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
$form = $('#personas');
$rows = $form.find('.person');
$('a#add').click(function() {
$rows.find(':first').clone().insertAfter($rows.find(':last'));
$justInserted = $rows.find(':last');
$justInserted.hide();
$justInserted.find('input').val(''); // it may copy values from first one
$justInserted.slideDown(500);
});
</script>
</head>
<body>
<form id="personas" name="personas" method="post" action="">
<table width="300" border="1" cellspacing="0" cellpadding="2">
<tr>
<td>Name</td>
<td>More?</td>
</tr>
<tr class="person">
<td><input type="text" name="name[]" id="name[]" /></td>
<td><a href="#" id="add">+</a></td>
</tr>
</table>
</form>
</body>
</html>
This will get you close, the add button has been removed out of the table so you might want to consider this...
HTML markup looks like this
EDIT To empty a value of a textbox after insert..
EDIT2 Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this
I will leave the rest to you!
I have Tried something like this and its works fine;
this is the html part :
this is Javascript part;
Finaly PHP submit part:
you can find more details via Dynamic table row inserter
As an addition to answers above: you probably might need to change ids in names/ids of input elements (pls note, you should not have digits in fields name):
I have done this having some global variable by default set to 0:
and in the add function after you've cloned and resetted the values in the new row:
Untested. Modify to suit:
This is better than copying innerHTML because you will lose all attached events etc.
Building on the other answers, I simplified things a bit. By cloning the last element, we get the "add new" button for free (you have to change the ID to a class because of the cloning) and also reduce DOM operations. I had to use filter() instead of find() to get only the last element.