删除表单中动态创建的元素

时间:2020-07-31 01:17:08

标签: javascript html

我知道这是一个基本问题,但是我正在制作一个动态表单,并且在弄清楚如何删除共享同一类的元素时遇到了一些麻烦。我在网上和其他帖子中四处寻找实现此目的的方法,但仍然无法弄清。

对此我是陌生的,因此我对基本问题表示歉意。在下面,我粘贴了相关的代码以及对此的尝试。谁能帮助我?

var ingCounter = 1;
var dirCounter = 1;
var limit = 10;

function addIngredient(divName){
    if (ingCounter == limit)  {
          alert("You have reached the add limit");
    }
    else {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "<div class='ingredientSet'><input class='ingredientInput' type='text' name='ingredients[]'><button class='deleteIngredientButton' type='button' onClick='removeElement('directionSet');'>X</button></div>";
          document.getElementById(divName).appendChild(newdiv);
          ingCounter++;
    }
}

function addDirection(divName){
    if (dirCounter == limit)  {
          alert("You have reached the add limit");
    }
    else {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "<div class='directionSet'><input class='directionInput' type='text' name='directions[]'><button class='deleteDirectionButton' type='button'>X</button></div>";
          document.getElementById(divName).appendChild(newdiv);
          dirCounter++;
    }
}

function removeElement(elementId) {
    // Removes an element from the document
    var element = document.getElementById(elementId);
    element.parentNode.removeChild(element);
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Homemade</title>

        <!-- Required program scripts -->
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
        
        <!-- Style Sheets-->
        <link rel="stylesheet" href="/styles/navBarStyle.css">
        <link rel="stylesheet" href="/styles/myRecipesStyle.css">
        <link rel="stylesheet" href="/styles/createRecipeStyle.css">
        <link rel="stylesheet" href="/styles/errorMessageStyle.css">
    </head>
    <body>
        <!-- Background image -->
        <img id="background" src="/images/foodBackground.jpg" alt="">

        <div id="newRecipeContainer">
            <div id="closeButtonContainer">
                <div id="backButton"><a id="back" href="/recipes/myRecipes">&larr; My Recipes</a></div>
            </div>
            
            <form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
                <label id="formSubHeading">Create Your Homemade Recipe</label>

                <%- include('../_partial/_messages'); -%>

                <div id="recipeNameContainer">
                    <label id="recipeNameLabel">Title</label>
                    <input id="recipeNameInput" type="text" name="recipeName">
                </div>

                <div id="recipeImage">
                    <label id="recipeImageLabel">Add An Image of Your Meal</label>
                    <input id="recipeImageInput" type="file" accept="image/*" name="recipeImage"/> 
                    <label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
                </div>

                <div id="recipeDescription">
                    <label id="recipeDescriptionLabel">Description</label>
                    <textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
                </div>

                <div class="ingredientsContainer">
                    <label id="ingredientsLabel">Ingredients</label>
                    <button id="addIngredientButton" type="button" onClick="addIngredient('allIngredients');">Add Another Ingredient</button>
        
                    <div id="allIngredients">
                        <div class="ingredientSet">
                            <input class="ingredientInput" type="text" name="ingredients[]">
                        </div>
                        
                    </div>
                </div>

                <div class="directionsContainer">
                    <label id="directionsLabel">Directions</label>
                    <button id="addDirectionButton" type="button" onClick="addDirection('allDirections');">Add Another Direction</button>
            
                    <div id="allDirections">
                        <div class="directionSet">
                            <input class="directionInput" type="text" name="directions[]">
                        </div>
                    </div>
                </div>
                
                <div id="createRecipeButtonContainer">
                    <button id="createRecipeButton" type="submit">Create Recipe</button>
                </div>
                
            </form>
        </div>
    </body>

    <!-- Required scripts to run app -->
    <script src="/controls/newRecipeControl.js"></script>
    <script src="/controls/errorMessageControl.js"></script>
</html>

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在您的代码中,您使用的是getElementById,但没有id称为directionSet的类。

您只需调用onClick函数,即可使用parentElementremove删除新添加的动态输入。

onClick函数removeElement()中-this指的是我们单击的元素,它将从表单中删除。

var ingCounter = 1;
var dirCounter = 1;
var limit = 10;

function addIngredient(divName) {
  if (ingCounter == limit) {
    alert("You have reached the add limit");
  } else {
    var newdiv = document.createElement('div');
    newdiv.innerHTML = "<div class='ingredientSet'><input class='ingredientInput' type='text' name='ingredients[]'><button class='deleteIngredientButton' type='button' onClick='removeElement(this);'>X</button></div>";
    document.getElementById(divName).appendChild(newdiv);
    ingCounter++;
  }
}

function addDirection(divName) {
  if (dirCounter == limit) {
    alert("You have reached the add limit");
  } else {
    var newdiv = document.createElement('div');
    newdiv.innerHTML = "<div class='directionSet'><input class='directionInput' type='text' name='directions[]'><button class='deleteDirectionButton' onClick='removeElement(this);' type='button'>X</button></div>";
    document.getElementById(divName).appendChild(newdiv);
    dirCounter++;
  }
}

function removeElement(elementId) {
  // Removes an element from the document
  elementId.parentElement.remove()
}
<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Homemade</title>
</head>

<body>
  <!-- Background image -->
  <div id="newRecipeContainer">
    <div id="closeButtonContainer">
      <div id="backButton"><a id="back" href="/recipes/myRecipes">&larr; My Recipes</a></div>
    </div>

    <form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
      <label id="formSubHeading">Create Your Homemade Recipe</label>

      <div id="recipeNameContainer">
        <label id="recipeNameLabel">Title</label>
        <input id="recipeNameInput" type="text" name="recipeName">
      </div>

      <div id="recipeImage">
        <label id="recipeImageLabel">Add An Image of Your Meal</label>
        <input id="recipeImageInput" type="file" accept="image/*" name="recipeImage" />
        <label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
      </div>

      <div id="recipeDescription">
        <label id="recipeDescriptionLabel">Description</label>
        <textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
      </div>

      <div class="ingredientsContainer">
        <label id="ingredientsLabel">Ingredients</label>
        <button id="addIngredientButton" type="button" onClick="addIngredient('allIngredients');">Add Another Ingredient</button>

        <div id="allIngredients">
          <div class="ingredientSet">
            <input class="ingredientInput" type="text" name="ingredients[]">
          </div>

        </div>
      </div>

      <div class="directionsContainer">
        <label id="directionsLabel">Directions</label>
        <button id="addDirectionButton" type="button" onClick="addDirection('allDirections');">Add Another Direction</button>

        <div id="allDirections">
          <div class="directionSet">
            <input class="directionInput" type="text" name="directions[]">
          </div>
        </div>
      </div>

      <div id="createRecipeButtonContainer">
        <button id="createRecipeButton" type="submit">Create Recipe</button>
      </div>

    </form>
  </div>
</body>

</html>