My code is aimed at creating a dynamic way to add and remove textboxes. However, I am encountering a problem where clicking the delete button removes everything instead of just one textbox. Can anyone spot the error in my code or offer a solution to remove one textbox at a time? Your help is greatly appreciated. Thank you in advance!
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dynamic Textbox Addition</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
$(document).ready(function () {
$('<button/>').attr({ 'id': 'add' }).appendTo("body");
$("#add").text("Add Field");
$('<div/>').attr({ 'id': 'items' }).appendTo("body");
$('<div/>').attr({ 'type': 'text', 'name': 'input[]' }).appendTo("#items");
$("#add").click(function (e) {
var text1 = $('<div/>').attr({ 'id':'div2','type': 'text', 'name': 'input[]' });
var text2 = $('<input/>').attr({ 'id': 'i1', 'type': 'text', 'name': 'username', 'size': '25' });
var text3 = $('<button/>').attr({ 'id': 'del' }).text("Delete");
$("#div2").append(text2, text3);
$("#items").append(text1);
$('<br/>').insertAfter(text3);
});
//Delete function
$("body").on("click","#del",function (e) {
$(this).parent("div").remove();
});
});
</script>
</head>
<body>
</body>
</html>