Delete a div when a button is clicked through JavaScript

I'm having an issue with a form I created that duplicates itself - I can't seem to get the 'x' button to remove the corresponding div as needed.

I have placed both buttons outside of the div like this:

<button type="button" id="cross" class="buttonImgTop" onclick="remChild()"></button>
<div id="ValuWrapper"> ...content goes here... </div>
<button type="button" class="buttonImg" onclick="repeat()"></button>

Every time the '+' sign is clicked to add more forms on the website, the 'x' button and 'div' are cloned and duplicated.

Below is the code for cloning the form and removing it:

<script>        
    var i = 0;
    var original = document.getElementById('ValuWrapper');
    var crossButton = document.getElementById('cross');
    var n = 0;

    function repeat() {
      var clone = original.cloneNode(true);
      var crossBut = crossButton.cloneNode(true);
      clone.id = "ValuWrapper" + ++i;
      crossBut.id = "cross" + i;
      crossButton.parentNode.appendChild(crossBut);
      original.parentNode.appendChild(clone);     
  
      n = i;

}

    function remChild(){

        for(i = 0; i <= n; i +=1)
        {
        $("#cross"+[i]).click(function () {
            $("#ValuWrapper"+[i]).slideUp(400, function () {
                    $("#ValuWrapper"+[i]).remove();
                    $(this).remove();
                });
          });
        }
    }
</script>

I want the 'x' button to trigger the animation 'slideUp()' on the specified div, then remove both the button and div in any order the client prefers. But it doesn't seem to be working as intended.

Answer №1

This appears to be the solution you are searching for.

In an effort to avoid hardcoding, I have implemented a method to count and remove sibling elements while also eliminating any inline event handlers that may cause issues.

$(function() {
  var $original = $('#ValuWrapper'),
    $crossButton = $('#cross'),
    $content = $("#content");

  $content.on("click", ".cross", function() {
    if ($(this).is("#cross")) return false;
    var $cross = $(this);
    $(this).next().slideUp(400, function() {
      $(this).remove();
      $cross.remove();
    });
  });

  $("#repeat").on("click", function() {
    $content.append($crossButton.clone(true).removeAttr("id"));
    $content.append(
      $original.clone(true)
      .hide() // if sliding
      .attr("id",$original.attr("id")+$content.find("button.cross").length)
      .slideDown("slow") // does not slide much so remove if you do not like it
    );
  });

});
#content { height:100%}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="content">
  <button type="button" class="buttonImgTop cross" id="cross">X</button>
  <div id="ValuWrapper"> 
    ...content comes here... <br/>
    ...content comes here... <br/>
  </div>
</div>
<button type="button" class="buttonImg" id="repeat">Add</button>

Answer №2

Here is the solution that you've been looking for. I have included the complete code in a single HTML file. Although no CSS has been applied yet, it is a functional example that meets your requirements. Feel free to customize the content as needed.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script> 
var i = 0;
var original; 
var crossButton ;
var n = 0;

function repeat() {
      var clone = original.cloneNode(true);
      var crossBut = crossButton.cloneNode(true);
      clone.id = "ValuWrapper" + ++i;
      crossBut.id = "cross" + i;
      $(crossBut).text("corss"+i);
      crossButton.parentNode.appendChild(crossBut);
          original.parentNode.appendChild(clone);     
          // used for remChild() function
          n = i; 
}

function remChild(obj){
    $($(obj).next()).slideUp(400,function()
    {
        $(obj).next().remove();
        $(obj).remove();
    });           
 }

$(document).ready(function(){
    original = document.getElementById('ValuWrapper');
    crossButton = document.getElementById('cross');

    $(".buttonImg").click(function(){
        repeat();
    });

    $("body").on("click",".buttonImgTop",function(){
        remChild(this);
    });
});       

</script>
<body>

<h2>My First JavaScript</h2>

<button type="button" id="cross" class="buttonImgTop" >remove</button>
<div id="ValuWrapper"> ...content comes here... </div>
<button type="button" class="buttonImg" >repeat</button>


</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Loop through an array of arrays in JavaScript. If a match is found, add it to an existing inner array. If not, create a new

I am currently extracting data from a database, and here is a simplified representation of the information: var example = [ {'start': 1966, 'end': 1970}, {'start': 1969, 'end': 1971}, {'start&ap ...

What is the most efficient way to transmit an HTML document element from a client to a server in Node JS

I am attempting to capture a snapshot of my client-side document object and send it to the Node.js server. However, when I try to convert it into a string using: JSON.stringify(document.documentElement) I encounter an issue where it becomes an empty obje ...

Ensure that text within openhtmltopdf is aligned to the right and any unnecessary white space at the

Currently, I am using the open source project openhtmltopdf but I have encountered a certain issue. Within a div-element, I have a p-tag with text-align: right styling. The text is aligned correctly to the right until there is a line break due to the widt ...

React Router - Changing the URL path without affecting the components displayed

Facing an issue with React Router where the main page renders but other pages do not. I am using a library called react-responsive-animate-navbar for the Navigation bar, which works well and changes the URL when clicked. However, the specified component fo ...

The next.js router will update the URL without actually navigating to a new page, meaning that it will still display the current page with the updated URL

My search results are displayed at the route /discovery, and I am working on syncing the search state with URL query parameters. For example, if a user searches for "chicken," the URL becomes /discovery?query=chicken&page=1. When a user clicks on a se ...

"Utilizing Jquery for interactive menu functionality - delivering the requested JSON

I have successfully implemented a dynamic menu using jQuery that parses a JSON response file to create the menu. However, instead of having the menu items link to URLs, I want them to retrieve and parse JSON data from those URLs. Despite my efforts, the me ...

Exploring the functionalities of jQuery within ajax-loaded content

My web page consists of the following code: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>test</title> <script src="jquery-2.1.1.min.js"></script& ...

Unusual $http Angular.js POST inquiry

Hey there, I'm facing a peculiar issue in my web development project. I have a table that acts as an input field where users can enter data and then send it back to the Spring Rest API. The data is received as a String and then parsed using the Gson l ...

Updating Rails modal fields via AJAX on the modal index page

Currently, I am attempting to update the modal fields on the modal index page. On this particular page, there are two dropdown fields associated with each ticket. The goal is for the modal field to be updated when the value of these dropdowns changes. htt ...

Utilizing the mobile navigation layout for desktop screens without the need to adjust breakpoints

Having created a responsive site with common breakpoints established in SCSS as mixins, I am now seeking to implement the mobile breakpoint for a single page on desktop view only. Initially, my plan was to create a 'forced-mobile' class by exten ...

Discovering targeted information from object utilizing React

When using the fetch method to retrieve film data, how can I extract specific details from the returned object? I am able to access and manipulate properties like name, genre, cast, trailers, and recommendations, but I'm struggling with retrieving the ...

Only conceal the breadcrumb trail on the 404 error page

I have recently created a custom node for my site's 404 page with the path /node/83 in the site information. However, I am facing an issue where I cannot hide the .breadcrumb element using display:none. I attempted to achieve this through CSS injector ...

Employ a unique filter within the controller of your AngularJs directive

Current Situation I currently have an array of users with their information and I am using ng-repeat along with a custom directive to create HTML user cards. The scope for each card is specific to the individual user. Within the user model, there is a v ...

Transmitting an image from an HTML file to a Node.js server

Hello, I am currently working on capturing frames from a video and converting them into images. However, I am encountering an issue when passing this image to server.js as I am unable to access it and the console shows its type as undefined. Below is the s ...

Show the present category name within breadcrumbs (utilizing angularJS)

Struggling to display category and vendor names on breadcrumbs? Utilizing the ng-breadcrumbs module but encountering difficulties in making curCategory and curVendor globally accessible. Tried various methods without success. Below is the HTML code snippe ...

Having difficulty retrieving items from Mongoose-Node database

I am currently working with a Mongodb database that stores resume objects. These objects contain various skills information and I have set up a node-express server to query the database based on specific skills. For example, when querying for a skill like ...

Can someone please explain how I can extract and display information from a database in separate text boxes using Angular?

Working with two textboxes named AuthorizeRep1Fname and AuthorizeRep1Lname, I am combining them in typescript before storing them as AuthorizeRep1Name in the database. Refer to the image below for the result. This process is used to register and merge the ...

Customizing response headers in vanilla Node.js

My Node.js setup involves the following flow: Client --> Node.js --> External Rest API The reverse response flow is required. To meet this requirement, I am tasked with capturing response headers from the External Rest API and appending them to Nod ...

Click on the submenu to expand it, then simply select the desired option to navigate

I have created a toggle menu that displays a list of child elements when clicked, and hides them if clicked again. However, when a child element is clicked, I want it to navigate to the corresponding page. I am having trouble getting this functionality to ...

How can I extract the document that is generated when a button is clicked using BeautifulSoup?

Trying to utilize BeautifulSoup for scraping my banking website to automatically retrieve the generated PDF from monthly purchases. Successfully logging in and reaching the page with the button, but the button does not seem to be a simple link - possibly a ...