Jerome Jerome - 5 months ago 12
HTML Question

Dynamically populating input text boxes and removing them using Jquery

When I click the

+
button, new text box with
+
and
-
buttons should appear and this
+
button itself should disappear.

When I click the
-
button, the text box must disappear and the previous
+
button should once again appear.

Help me with making the previous buttons appear and disappear accordingly.

Here is code I have done so far:



$(document).ready(function() {

var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");


$(add_button).click(function(e) {
e.preventDefault();

var append1 = $(wrapper).append('<div><input type="text" name="mytext[]"/><button class="add_field_button1">+</button><button class="remove_field">-</button></div>');
$(".add_field_button").hide();

});

$(wrapper).on("click", ".remove_field", function() {

$(this).parent('div').remove();

})
$(wrapper).on("click", ".add_field_button1", function() {

$("#inputfield").append('<div><input type="text" name="mytext[]"/><button class="add_field_button">+</button><button class="remove_field">-</button></div>');

})
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<div id="inputfield">
<input type="text" name="mytext[]">
<button class="add_field_button">+</button>
</div>
</div>




Answer

DEMO LINK

var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");

$('body').on("click", '.add_field_button', function (e) {
    var _this = $(this);
    e.preventDefault();
    _this.hide();
    _this.closest('.row').find('.remove_field').hide();

    var append1 = $(wrapper).append('<div class="row"><input type="text" name="mytext[]"/><button class="add_field_button">+</button><button class="remove_field">-</button></div>');


})


$(wrapper).on("click", ".remove_field", function () {
    var _row = $(this).closest('.row');
    _row.prev('.row').find('button').show();
    _row.remove();
})
.hidden{
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap row">

    <div class="row">
    <input type="text" name="mytext[]">
    <button class="add_field_button">+</button>
    </div>

</div>