remove a textbox dynamically in jquery without using any javascript -
here code, tried create dynamically add/remove textbox. when click delete button deleted, should (or pls specify error in code.) want remove 1 one.. can tell me? in advance..
<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>dynamic add button</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) { //append new row of code "#items" div 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>
jquery javascript, think mean. here jsfiddle: http://jsfiddle.net/wfthf2qc/
the problem kept same id of text fields (#div2
) when appended new field, jquery kept appending first occurrence of #div2
. when call delete function, deletes parent div contains of fields.
in code created count
variable keeps counting each time "add" button clicked , using create unique div names (div1, div2, div3, etc), jquery knows append new field.
i moved $("#items").append(text1);
before $("#div" + count).append(text2, text3);
putting after makes first click "add" button fail, not have div containers append to.
$("#items").append(text1); $("#div" + count).append(text2, text3); $('<br/>').insertafter(text3);
personally think there may more elegant solution didn't want change code much
Comments
Post a Comment