使用 Javascript 删除表单域

Remove Form Field With Javascript

所以我浏览了该网站,但没有找到我的特定问题的答案。我是编写代码的新手,正在尝试弄清楚如何在添加了 Javascript 后删除表单字段。这是代码。我将不胜感激 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>

也许这有帮助?在这里勾选 link link

var counter = 1;
var limit = 2;

    function addInput(Favorites) {
      if (counter == limit) {
        removeInput();
        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() {
        var x = document.querySelector('#Favorites div:last-child');
        x.remove();
        --counter;
      }
    }

您的代码中存在各种问题,因此我对其进行了一些修改。所以使用下面的js代码

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;  
}

在html中你可以稍微修改一下你的代码

 <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>

在此处查看上面的代码
https://jsbin.com/hizimateri/1/edit?html,js,console,output

如果您有任何问题。让我知道。