Skip to content

Instantly share code, notes, and snippets.

@abidvf
Created April 2, 2019 04:37
Show Gist options
  • Save abidvf/e41213b35f61e72871dd3602d7b90ceb to your computer and use it in GitHub Desktop.
Save abidvf/e41213b35f61e72871dd3602d7b90ceb to your computer and use it in GitHub Desktop.
Add dynamic form fields
<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>
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).click(function(e) {
$('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
});
$('.multi-field .remove-field', $wrapper).click(function() {
if ($('.multi-field', $wrapper).length > 1)
$(this).parent('.multi-field').remove();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment