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

3

我知道这是一个基础问题,但我正在制作一个动态表单,并且在尝试删除共享相同类的元素时遇到了一些困难。我已经在网上搜索和查看了其他帖子,但仍然无法弄清楚如何实现。

我是新手,对于这个基本问题表示歉意。以下是相关代码和我的尝试。是否有人能够帮助我?

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个回答

1
在你的代码中,你使用了 getElementById,但是没有叫做 directionSetid,它是一个类。
你可以简单地使用 parentElementremove 调用一个 onClick 函数来删除新增加的动态输入框。
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>


谢谢您的解释,让我很明白! - halsheikh
1
@halsheikh 很高兴我能帮到你。祝你编程愉快。 - Always Helping

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接