简体   繁体   中英

Remove dynamically created elements in a form

I know this is a basic questions, but I am working on making a dynamic form and was having a bit of trouble figuring out how to delete elements that share the same class. I have looked around on the web and other posts for a means to accomplish this, but still was unable to figure it out.

I am new to this so I apologize for the basic question. Below, I have pasted the relevant code and my attempt at this. Would anyone be able to assist me?

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>

Thanks for any help.

In your code you are using getElementById but there is no id called directionSet its a class.

You can simply use parentElement and remove to remove the newly added dynamic inputs by calling an onClick function.

In the onClick function removeElement() - this refers to the elements we have clicked and it will remove from the form.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM