This generates a new text box with a unique id if you hit the Add button, but if you hit the remove button it removes the last text box.
Try it:
The count function counts the current text boxes, I used XPATH for this and then iterate trough the results to count them.
Try it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<!DOCTYPE html> <html> <script> var elements = 0; function count(elem){ elements=0; var xPathRes = document.evaluate ('//div[@id="'+elem+'"]/div', document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); var actualSpan = xPathRes.iterateNext (); while (actualSpan) { ++elements; actualSpan = xPathRes.iterateNext (); } } function add(elem) { count(elem); if(elements <=10){ document.getElementById(elem).innerHTML+='<div id="SPECIAL_DIV_'+elements+'" >TB'+elements+':<input type="text" id="SPECIAL_TB_'+elements+'" ></div>'; } } function del(elem) { count(elem); if(elements >=1){ document.getElementById("SPECIAL_DIV_"+(elements-1)).remove(); } } </script> <body> <button onclick="add('demo');">Add</button> <button onclick="del('demo');">Remove</button> <br> <div id="demo"> </div> </body> </html> |