JavaScript generate and delete html inputs

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:

   
<!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>
The count function counts the current text boxes, I used XPATH for this and then iterate trough the results to count them.

Leave a Reply

Your email address will not be published.

16 − 6 =