Search code examples
javascriptformsappendchildremovechild

Remove Form Field With Javascript


So I Have Looked Through The Site Only To Not Find The Answer For My Particular Problem. I Am Pretty New To Writing Code And Am Trying To Figure Out How To Remove A Form Field After Its Been Added with Javascript. Here is the code. I would Greatly Appreciate Feedback/Solutions.

var counter = 1;
var limit = 1000;
function addInput(Favorites){
       if (counter == limit)  {
            alert("You have reached the limit of adding " + counter + " inputs");
       }
       else {
            var newdiv = document.createElement('div');
            newdiv.innerHTML = "<br>Favorite " + (counter + 1) + "<input type='text' name='Favorites[]'><input type ='button' value ='Remove'>";
            document.getElementById(Favorites).appendChild(newdiv);
            counter++;

      }

      function removeInput(newdiv){
          document.getElementById('Favorites').removeChild(newdiv);
          counter - 1;
      }
}
  <form>
       <div id="Favorites">
            Favorite 1<input type="text" name="Favorites[]">
       </div>
      <input type="button" value="Add New Favorite" onClick="addInput('Favorites');">
      <input type = "button" value = "Save Changes">
</form>


Solution

  • there are various issues in your code so I have modified it a bit. So use following js code

    var counter = 1;
    var limit = 1000;
    function addInput(){
       if (counter == limit)  {
            alert("You have reached the limit of adding " + counter + " inputs");
       }
       else {
                var newdiv = document.createElement('div');
                newdiv.innerHTML = " <div class='inputElement'>Favorite " + (counter + 1) + "<input type='text' name='Favorites[]'><input type ='button' value ='Remove' onClick='removeInput(this)'></div>";
                document.getElementById("Favorites").appendChild(newdiv);
                counter++;
         }
    }
    
    function removeInput(removeLink){
       var inputElement = removeLink.parentNode;
      inputElement.remove();
      counter= counter - 1;  
    }
    

    In html you can modify your code a bit

     <form>
       <div id="Favorites">
         <div class='inputElement'>   
            Favorite 1<input type="text" name="Favorites[]">
         </div>  
        </div>
          <input type="button" value="Add New Favorite" onClick="addInput();">
         <input type = "button" value = "Save Changes">
    </form>
    

    Check out above code here
    https://jsbin.com/hizimateri/1/edit?html,js,console,output

    If you have any issues with it . Let me know.