Add/Remove Input Fields Dynamically with jQuery
HTML
<form role="form" action="/wohoo" method="POST">
<label>Stuff</label>
<div class="multi-field-wrapper">
<div class="multi-fields">
<div class="multi-field">
<input type="text" name="stuff[]">
<!-- <button type="button" class="remove-field">Remove</button> -->
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
JavaScript
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).click(function(e) {
var $el = $('.multi-field:first-child', $wrapper).clone(true);
var $removeButton = $('<button type="button" class="remove-field">Remove</button>');
$removeButton.click(function() {
if ($('.multi-field', $wrapper).length > 1)
$(this).parent('.multi-field').remove();
});
$el.append($removeButton);
$el.appendTo($wrapper).find('input').val('').focus();
});
});