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

Encountering a TypeScript error when attempting to utilize indexOf on a Typed Array, leading to restriction

I have been working with an Interface, where I created an array of type Interface. I am currently facing some IDE error complaints when trying to use the .indexOf method on the Array. These errors seem confusing to me, and I'm hoping someone here migh ...

How to set up 'ng serve' command in Angular to automatically open a private browsing window?

I am looking for a way to open my project in an Incognito Mode browser without storing any cache. Is there a specific Angular CLI flag that can be included in the ng serve -o command or in the Angular CLI configuration file to enable opening a browser in ...

What is the best way to update or change a value in a JSON file?

This specific file is structured in JSON format shown below: { "ClusterName": { "Description": "Name of the dbX Cluster", "Type": "String", "MinLength": "1", "MaxLength": "64", "AllowedPattern": "[-_ a-zA-Z0-9]* ...

Issue with interactive rows in a table ( Rails Version 4 )

I am encountering an issue with a table that is linked to a customer show page _table.html.erb <table class="table table-striped table-bordered table-hover table-condensed"> <thead> <tr> <th width="50"><%= sort_link ...

How can jQuery be utilized to enlarge specific <li> elements that are aligned with the right side of the page?

I'm encountering issues with expanding list elements using jQuery. The lists consist of social media icon links that I would like to enlarge upon mouseover. The problem arises when enlarging the width of the li element, causing the ul to also expand. ...

When a .post() request receives a numerical response, it is increasing by a factor of 10

Currently, I am utilizing the Wordpress ajax api to transmit the output of a php function to the client through .post() ajax. The issue arises when the value returned includes an extra 0 alongside the actual numeric value. For instance, if the numeric valu ...

Manipulate CSS Properties with Javascript Based on Dropdown Selection

I am currently working on implementing a feature that involves changing the CSS property visibility: of an <input> element using a JavaScript function triggered by user selection in a <select> dropdown. Here's what I have so far in my cod ...

What is the best way to send parameters to a controller using jQuery?

I have a controller action that requires a String parameter from the view. Within the view, there is a hyperlink with an onclick event that should trigger a jQuery function to send that value to the action. $(function () { debugger; ...

Determine the selected radio button

----EDIT---- I am developing a jQuery mobile application and I need to determine which radio button is selected. This is the JavaScript code I'm using: function filter(){ if(document.getElementById('segment1').checked) { aler ...

The check is ineffective: if (isset ($_PHP["form_name"]))

I believe there is an issue with the form validation in the file. It seems that all forms with queries are being executed without proper checks. The code snippet below shows my attempt to address this using if (isset($_POST ['form_name'])), but i ...

Exploring the intricacies of extracting nested JSON data in TypeScript

Can someone help me with this issue? https://example.com/2KFsR.png When I try to access addons, I only see [] but the web console indicates that addons are present. This is my JSON structure: https://example.com/5NGeD.png I attempted to use this code: ...

Enhance your Angularfire experience with $firebaseArray by enabling dynamic counting and summing

Is there a way to dynamically count certain nodes if they are defined? The current implementation requires explicitly calling sum(). app.factory("ArrayWithSum", function($firebaseArray) { return $firebaseArray.$extend({ sum: function() { var ...

Using $_POST method to navigate within the same web page

<!doctype html> <html> <head> <meta charset="UTF-8"> <title>PHP links</title> <?php echo '<div style="background-color:#ccc; padding:20px">' . $_POST['message'] . '</div>'; ...

Error: Unable to access property 'fetch' of null (discord.js)

Hey there, I'm running into an issue where it's giving me an error saying that the property 'fetch' doesn't exist. I'm using the Replit database for a balance command in discord.js. You can see the error image here. Here is t ...

Wordpress causing Jquery to malfunction; PHP function not executing

Looking to incorporate a script into my WordPress function.php file. Here's what I have so far: <?php function add_google_jquery() { if ( !is_admin() ) { wp_deregister_script('jquery'); wp_register_script('jquery', ...

The issue of "undefined is not a function" is arising when trying to use the session in NHibernate with a mongo store

In my MongoDB database, I have a collection named 'Sessions' within the 'SessionStore' to store session state. To manage sessions, I am using express-session. Below is the code snippet used to set up sessions: var session = requi ...

What is the process for appending a URL parameter to the existing URL in a React application?

Presently, I am working within the Post component and using the Fetch API to retrieve data from the "/home" route. componentDidMount() { fetch('/home') .then(res => res.json()) .then((data)=> { console.log(data.ports) ...

Search a location database using the user's current coordinates

Currently, I am working on a project that involves a database containing locations specified by longitude and latitude. Upon loading the index page, my goal is to fetch the user's location and then identify every point within a certain distance radius ...

The JSON dataset is displaying an undefined value

I am attempting to utilize the Reddit API to display data. However, when I try to show it on an alert, it returns as undefined. <!DOCTYPE html> <html> <body> <h2>Creating Object from JSON String</h2> <p id="demo">&l ...

Update with the string before it in a JSON list

Within a JSON file, I came across an array that requires the 'TODO' placeholder to be replaced with the entry above it. To elaborate, the initial "TODO" should be substituted with "Previous question" and the subsequent one with "Next question". ...