I am trying to create a form that allows a user to enter a series of emails by dynamically adding a new text field. I have followed this implementation of here which works well.:
https://stackoverflow.com/questions/34748659/dynamically-add-and-remove-textboxes-and-get-value-of-dynamic-textbox-using-jque
The one change i made which suddenly make the "remove" button not work is adding a label between the input fields as below:
jQuery(document).ready( function () {
$("#append").click( function(e) {
e.preventDefault();
var urlParams = new URLSearchParams(window.location.search);
var domain = urlParams.get('domain');
//console.log(domain);
// document.getElementById('domain').innerHTML = domain;
$(".inc").append(`<div class="controls">\
<input class="form-control" type="text" id="email" name="email" placeholder="email">\
<labe>@</label>\
<input class="form-control" type="text" id="domain" name="domain" disabled="disabled" value="${domain}">\
<a href="#" class="remove_this btn btn-danger">remove</a>\
<br>\
<br>\
<br>\
</div>`
);
return false;
});
jQuery(document).on('click', '.remove_this', function() {
jQuery(this).parent().remove();
return false;
});
$("input[type=submit]").click(function(e) {
e.preventDefault();
$(this).next("[name=textbox]")
.val(
$.map($(".inc :text"), function(el) {
return el.value
}).join(",\n")
)
})
});
The problem is the "remove" button now only removes :
<labe>@</label>\
<input class="form-control" type="text" id="domain" name="domain" disabled="disabled" value="${domain}">\
while leaving the first text box:
<input class="form-control" type="text" id="email" name="email" placeholder="email">\
id="email"andid="domain"into classes, since you can't reuse the same ID, which will happen once you add more than one input. This isn't the problem, but just a note to learn about<labe>should be<label>