1
<html>

<head>
    <title></title>
    <script>
    function show() {
        var textbox = document.createElement('input');
        textbox.type = 'text';
        textbox.id = "textBox";
        var btn = document.createElement("button");
        btn.innerHTML = "X";
        btn.id = "button";
        btn.onclick = close;
        document.getElementById("display").appendChild(textbox);
        document.getElementById("display").appendChild(btn);
    }

    function close() {
        document.getElementById("textBox").style.display = "none";
        document.getElementById("button").style.display = "none";
    }
    </script>
</head>

<body>
    <a href="#" onclick="show()">add contact</a>
    <div id="display">
    </div>
</body>

</html>

In this code I was manged to generate the textbox with a button. when we click on the button in the first generating textbox button pair it is working. but it is not working or multiple pairs. I need to close each pair by clicking the button in the each pair.

ButchMonkey
  • 1,873
  • 18
  • 30
harry
  • 39
  • 2
  • Possible duplicate of [Adding input elements dynamically to form](https://stackoverflow.com/questions/14853779/adding-input-elements-dynamically-to-form) – chandu komati Nov 26 '19 at 09:46

1 Answers1

0

The attribute id must be unique in a document, use class instead to refer multiple elements with same attribute. You can use this object to refer the currently clicked button so that you can remove the correct element.

Try the following way:

function show(){
  var textbox = document.createElement('input');
  textbox.type = 'text';
  textbox.id = "textBox";
  var btn =document.createElement("button");
  btn.innerHTML ="X";
  btn.class="button";
  btn.onclick = close;
  document.getElementById("display").appendChild(textbox);
  document.getElementById("display").appendChild(btn);
}
function close(){
  this.previousElementSibling.remove();
  this.remove();
}
<a href="#" onclick = "show()">add contact</a>
<div id = "display"></div>

Please Note: previousElementSibling is not supported until IE9.

In that case please refer: parentNode or previousElementSibling not working in IE8

Mamun
  • 66,969
  • 9
  • 47
  • 59
  • The previousElementSibling property is not supported in IE8 and earlier versions. – Kankatala Krishna Nov 26 '19 at 09:52
  • @harry, if the answer solve your question then you can upvote and accept the answer by *clicking on the check mark beside the answer to toggle it from greyed out to filled in*...thanks:) – Mamun Dec 02 '19 at 06:37