I created a dynamic form which adds 3 new input fields if the user clicks a button. However, my delete button deletes the first added fields, which I don't want. How can I delete the last added input fields?
Below is my code for adding and deleting the fields.
$(document).ready(function () {
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 0; //initial count
$(add_button).click(function (e) {
e.preventDefault();
x++;
$(wrapper).append('<div id="names">Name: <input type="text" name="names[]"/></div>');
$(wrapper).append('<div id="ages">Age: <input type="text" name="ages[]"/></div>');
$(wrapper).append('<div id="numbers">Number: <input type="text" name="numbers[]"/><br><br></div></div>');
});
$(wrapper).on("click", ".remove_person", function (e) {
e.preventDefault();
if(x > 0) {
$("#names").remove();
$("#ages").remove();
$("#numbers").remove();
x--;
}
})
});
Below is my code for the fields in the HTML.
<b>People:</b><br>
<div class="input_fields_wrap" id="input_fields_wrap">
<button class="add_field_button">ADD</button>
<button id="remove_person" class="remove_person">REMOVE</button>
<br>
</div>
x)closestto remove the wrapper the button is in (so have a wrapper for each person)