Created
October 25, 2013 17:07
-
-
Save asperling/7158162 to your computer and use it in GitHub Desktop.
Add/Remove Input Fields Dynamically with jQuery
Try: http://jsfiddle.net/aaki/hMJEy/1/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function() { | |
$('.multi-field-wrapper').each(function () { | |
// Save context | |
var $wrapper = $('.multi-fields', this); | |
// Handle add button | |
$(".add-field", $(this)).click(function (e) { | |
$('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus(); | |
}); | |
// Handle remove button | |
$('.multi-field .remove-field', $wrapper).click(function () { | |
if ($('.multi-field', $wrapper).length > 1) $(this).parent('.multi-field').remove(); | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment