0

Here i want to add new textbox on click of button i.e btnAdd and and also want to remove those newly added textbox by clicking the button i.e btnRemove which is also added along with the new added textbox on a click of btnAdd .
Now the problem is that as i click the add button i.e btnAdd new textbox along with remove button i.e btnRemove is also added as required but as i click on remove button i.e btnRemove the respective textbox and that respective remove button is not removed.

Below is what i have done

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id="a">
    <input id="Text1" type="text" />
</div>
<input id="btnAdd" type="button" value="Add" />
<script>
    $(document).ready(function () {
        $("#btnAdd").click(function () {
            $("#a").append('<input type="text" id="Text1" value="" />'+'<input type="button" id="btnRemove" value="Remove"/>');
        });
        $('#btnRemove').click(function () {
            $('#Text1').remove();
            $(this).remove();
        });
    });
</script>
</body>
</html>
CrossWords
  • 47
  • 3
  • 9
  • Use [Event Delegation](http://learn.jquery.com/events/event-delegation/) for dynamically generated elements – Satpal Jan 19 '17 at 11:10
  • Refer: [Dynamically create textbox and remove them using jquery](https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=0ahUKEwix9dSpic7RAhVJLo8KHc1_COgQFggcMAE&url=http%3A%2F%2Fwww.aspsnippets.com%2FArticles%2FDynamically-add-and-remove-TextBoxes-using-jQuery.aspx&usg=AFQjCNGVXWPbc-JJBHIFviSebDP4ZLayyw&bvm=bv.144224172,d.c2I) – Sorangwala Abbasali Jan 19 '17 at 11:11
  • your script will not work as you are trying to assign same id again in while generating dynamic elements. you should make use of "Class" and "name" attribute instead – K D Jan 19 '17 at 11:12

1 Answers1

0

Add a class for remove button. Let it be btnRemove. Since this is a dynamically generated item, the event need to be delegated while removing the item.

In your case $(this).remove() will remove the the button , but it is required to remove the input box and the button also. So it is better to wrap everything inside a div & target to remove this wrapper div on click of remove button

hope this snippet will be useful

$(document).ready(function() {
  $("#btnAdd").click(function() {
    $("#a").append('<div class="con"><input type="text" id="Text1" value="" />' + '<input type="button" class="btnRemove" value="Remove"/></div>');
  });
  // delegating event here
  $('body').on('click','.btnRemove',function() {
    $(this).parent('div.con').remove()

  });
});

DEMO

brk
  • 48,835
  • 10
  • 56
  • 78