Reputation: 463
Is there an easier way in JQuery to dynamically add and remove fields for more than one field within the same form? I have two form elements in the same form that I'd like to have the ability to add and remove blank fields to.
<div class="col-sm-3">
Email<g:field type="email" name="Email" class="form-control" required="" value="" aria-labelledby="Email-label"/>
</div>
<div class="col-sm-2">
Fax<g:field type="tel" name="Fax" class="form-control" required="true" value="" aria-labelledby="Fax-label"/>
</div>
I have cobbled together this javascript piece from several different places and it works just fine for the first field, but when I try to duplicate it for the second one it doesn't work.
$(document).ready(function(){
$("#add").click(function (e) {
$("#submitterEmail").append('<div><input type="text" name="submitterEmail[]"><button class="delete">Delete</button></div>');
});
$("body").on("click", ".delete", function (e) {
$(this).parent("div").remove();
});
});
Upvotes: 1
Views: 2733
Reputation: 36699
Here's the JavaScript based on the HTML you have:
$(document).ready(function(){
$("#add").on("click", function(){
$("#container").append(
"<div class='col-sm-3'><g:field>Another field <button class='delete'>Delete</button></div>"
);
});
$(document).on("click", ".delete", function(){
$(this).parent().parent().remove();
});
});
Upvotes: 1