0

I am trying to create TextBoxes using Javascript on button click and then on another button click, I am trying to delete them. But the problem arises when I am trying to delete the TextBoxes. Button Click always creates the Textboxes without a hitch but the same doesn't happen consistently while I am trying to delete. Plz Help!!

  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Untitled Document</title>
   <script>
   var i=0;
    function create_txt()
    {
    var a=document.createElement("div");
    a.setAttribute("id",'d'+i);
    var b=document.createElement("input");
    b.setAttribute("id",'t'+i);
    a.appendChild(b);
    i++;

    var c=document.getElementById("pa1");
    c.appendChild(a);   

    }

  function delete_txt()
    {
    var x=document.getElementById('d'+i);
    var y=document.getElementById('t'+i);
     i--;
    x.removeChild(y);

   }
   </script>
   </head>

   <body>
   <div id="pa1"></div>
   <input type="button" onclick="create_txt()" value="Create" onclick="create_txt()"/>
   <input type="button" onclick="delete_txt()" value="Delete" onclick="delete_txt()" />
   </body>
   </html>

2 Answers 2

1

Your global var i is most likely the culprit - after creating the textboxes you increment i, but when you call delete you never decrement i until after. There are no id's that match! Try decrementing i before you get the textboxes to delete:

function delete_txt()
{
i--;
var x=document.getElementById('d'+i);
var y=document.getElementById('t'+i);

x.removeChild(y);

}

Yep: http://jsfiddle.net/3HH6E/

Sign up to request clarification or add additional context in comments.

Comments

0

Can you remove i altogether by just appending the DIVs and INPUTs into a unique DIV (#myInputs)? When deleting, you would just find the last set of DIV/INPUT inside of #myInputs.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.