0

I have two text boxes and two buttons named add and remove. The requirement is to add more boxes along with the current boxes. i somehow managed to add boxes but the requirement of removing the boxes is not working. Please help to why this code is not working and if possible suggest a working solution.

function addFunction(){
  var element = document.createElement("input");
  var parent = document.getElementById("form1");
  parent.appendChild(element);
}

function removeFunction(){
  var child = document.getElementsByTagName("input");
  var parent = document.getElementById("form1");

  for (var i = 0; i > child.length; i++) {
    parent.removeChild(child[i]);
  };
}
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <form id="form1" style="margin-left: 40%; margin-top: 100px;">
      <input type="text" id="one"><br><br><br>
      <input type="text" id="two"><br>
      <p id ="demo"> </p>
    </form>
    <button style="margin-left: 40%;" type="button" value="ADD" id="addButton" onclick="addFunction()">ADD</button>
    <button style="margin-left:50px;" type="button" value="REMOVE" id="removeButton" onclick="removeFunction()">REMOVE</button>
  </body>
</html>

1

3 Answers 3

1
for (var i = 0; i <  child.length; i++) {
        parent.removeChild(child[i]);
    };

You have got wrong condition in your for loop. Your i is always 0 at start, and is lesser then length of array with node elements, so loop just can't start. P.s. and you don't need var i before it

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

Comments

1

Your for-Loop is wrong:

        for (var i = 0; i > child.length; i++) {
            parent.removeChild(child[i]);
        };

You need to change ">" to "<"

Comments

1

Replace your > condition in the for loop with <. You want the for loop to be executed until it reach child.length.

1 Comment

yeah i did it but its saying that my up votes are recorded but it wont be shown publicly since i have less than 15 reputations..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.