Removing div dynamically using jQuery

I have a dynamic div creation issue when using the clone function. I added a remove button that should remove only the clicked div, but instead it is removing all of them. Check out the code below for reference:

http://jsfiddle.net/RZ36c/4/

<div class="container">
    <div class="row">
        <div class="col-xs-6">
            <form class="form-horizontal" role="form">
                <div id="0" class="address"> 
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Address Line1</label>
                        <div class="col-sm-10">
                            <input class="form-control" type="text" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Address Line2</label>
                        <div class="col-sm-10">
                            <input class="form-control" type="text" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">City</label>
                        <div class="col-sm-10">
                            <input class="form-control" type="text" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">State</label>
                        <div class="col-sm-10">
                            <input class="form-control" type="text" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Post Code</label>
                        <div class="col-sm-10">
                            <input class="form-control" type="text" />
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button class="btn btn-danger btn-remove"><i class="glyphicon glyphicon-remove-sign"></i>Remove</button>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button class="btn btn-default btn-add"><i class="glyphicon glyphicon-plus-sign"></i>Add</button>
                        <button class="btn btn-success btn-add"><i class="glyphicon glyphicon-floppy-save"></i>Submit</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

JavaScript

var id = 0;
$(".btn-add").click(function (event) {
    event.preventDefault();
    var cloneId = $('#' + id);

    //clone to new Address form
    var newAddressForm = cloneId.clone();
    //increase id
    id++;
    // change Id of new form
    newAddressForm.attr("id", id);

    //set input value to null/empty
    newAddressForm.find('input').val('');
    newAddressForm.insertAfter(cloneId);
});

$(".address input:button").click(function (event) {
    event.preventDefault();

    $(this).parent('div').remove();
});

Answer №1

I have updated the solution below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-xs-6">
                <form class="form-horizontal" role="form">
                    <div id="0" class="address">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Address Line1</label>
                            <div class="col-sm-10">
                                <input class="form-control" type="text" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Address Line2</label>
                            <div class="col-sm-10">
                                <input class="form-control" type="text" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">City</label>
                            <div class="col-sm-10">
                                <input class="form-control" type="text" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">State</label>
                            <div class="col-sm-10">
                                <input class="form-control" type="text" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Post Code</label>
                            <div class="col-sm-10">
                                <input class="form-control" type="text" />
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button class="btn btn-default btn-add"><i class="glyphicon glyphicon-plus-sign"></i>Add</button>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button class="btn btn-success"><i class="glyphicon glyphicon-floppy-save"></i>Submit</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <script>
        var id = 0;
        $(document).on('click', '.btn-add', function (event) {
            event.preventDefault();

            var field = $(this).closest('.address');
            var field_new = field.clone();

            $(this)
                .toggleClass('btn-default')
                .toggleClass('btn-add')
                .toggleClass('btn-danger')
                .toggleClass('btn-remove')
                .html('<i class="glyphicon glyphicon-remove-sign"></i>Remove');

            field_new.find('input').val('');
            field_new.insertAfter(field);
        });
        $(document).on('click', '.btn-remove', function (event) {
            event.preventDefault();
            $(this).closest('.address').remove();
        });
    </script>
</body>
</html>

Answer №2

This piece of code is effective

 let identifier = 0;
$(".btn-add").click(function (event) {
    event.preventDefault();
    let clonedId = $('#' + identifier);

    //copy to a new form
    let newForm = clonedId.clone(true);
    //increment identifier
    identifier++;
    // change Id of new form
    newForm.attr("id", identifier);

    //set input values to null/empty
    newForm.find('input').val('');
    newForm.insertAfter(clonedId);
});

$(".btn-remove").click(function(e){
    e.preventDefault();
    $(this).closest('.address').remove();
});

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

Calculate the frequency of tag_name occurrences on a webpage using Python and Selenium

Greetings! I am currently working with the following code snippet: for each in driver.find_elements_by_xpath(".//*[@id='ip_market" + market + "']/table/tbody") cell = each.find_elements_by_tag_name('td')[0] cell2 = each.find_el ...

Expand or collapse Angular Material Accordion depending on selected Radio button choice

Is it possible to use a mat-accordion with radio buttons where each panel expands only when its corresponding radio button is selected? I have the radio buttons functioning correctly, but the panels are expanding and collapsing with every click rather than ...

What is the best way to position my div outside of the wrapper while keeping the text inside?

For example: https://i.sstatic.net/UyhOl.png I want the blue text that says "join our discord server" to extend to 100% width when it's placed inside the wrapper. The reason it's inside the wrapper is to ensure the text matches up perfectly with ...

Adaptive video player for complete YouTube experience

Is there a way to incorporate a YouTube video as the background of a div, similar to how it is done on this site, using a <video> tag and ensuring that the video "covers" the entire div without any empty spaces while maintaining its original ratio? ...

Learn how to display HTML content in trNgGrid using the $sce.trustAsHtml method

I am currently working with a table that has search options implemented using trNgGrid.js. The data for this table comes from a Sharepoint list where one of the columns contains HTML content that I need to display. To achieve this, I attempted using $sce. ...

Embedded iframe links failing to open within the designated frame

I have encountered an issue on my website where the links under the portfolio section now open in a new window instead of the intended iframe. This change occurred suddenly without any alterations to the code. Despite closely examining and trying various ...

Discover the Magic Trick: Automatically Dismissing Alerts with Twitter Bootstrap

I'm currently utilizing the amazing Twitter Bootstrap CSS framework for my project. When it comes to displaying messages to users, I am using the alerts JavaScript JS and CSS. For those curious, you can find more information about it here: http://get ...

Unraveling the Mystery of CSS3 or JavaScript Sliders

I am currently developing a new website and I was intrigued by the slider effect on Apple and IBM's websites. For reference, you can check out how it works on sites like: and I noticed that the text and images slide in opposite directions, which se ...

What steps can I take to ensure a JavaScript loading image is displayed until the entire page has finished loading?

Looking to implement a JavaScript loading image that displays until the page has fully loaded? I'm currently developing an online antivirus scanner and in need of help. I am trying to set up JavaScript to show a loading image while a file is being up ...

JavaScript code that moves the active link to the top of the navigation when the window width is less than or equal to 800px

I'm working on a responsive navigation that is fixed at the top and switches from horizontal to vertical when the screen size is less than or equal to 800 pixels wide. However, I'm facing an issue with moving the active link to the top of the na ...

Switch between links with jQuery

I am looking to dynamically switch the classes on a few links. Take a look at the code below: <ul class="inline toggleNav"> <li><a class="active" id="imagesLink" href="#">Images</a></li> <li><a class="noLink" ...

The binding in Knockoutjs is working properly, but for some reason the href attribute in the anchor tag is not redirecting to

Here is the HTML code snippet I am working with: <ul class="nav nav-tabs ilia-cat-nav" data-toggle="dropdown" data-bind="foreach : Items" style="margin-top:-30px"> <li role="presentation" data-bind="attr : {'data-id' : ID , 'da ...

Conceal particular information within a repeated sequence and reveal it within a secret panel

I am working on a component that needs to show a hidden form when a specific content is clicked. I have successfully achieved this functionality, but now I also need to hide the original content div and display the hidden form in its place without affect ...

positioning a div based on the location of another div

I am currently working on aligning a div that sits at the bottom of all other divs. The last div is set to float and aligned at the top using CSS. I am unsure how to align it from the left side without any issues when the screen resolution changes. Is th ...

"We encountered an error with the external script while trying to load file content using jQuery's ajax function. It

//C.php <script type="text/javascript"> $(document).ready(function(e) { $('div').load("D.php"); }); </script> <div></div> //D.php <script type="text/javascript" src="D.js"></script> //D.js console.log(45 ...

Tips for generating rows in an HTML table

I'm attempting to generate a table with 5 rows and 4 columns, displaying increasing multiples of a user-input number. While I can print the numbers successfully, they all appear in one column. I thought breaking up the loops would solve this issue, bu ...

Header 1 is not receiving any special styling, while Headers 2 through 6 are being styled accordingly

I am currently utilizing Skeleton V2.0.4 to design a landing page, but I seem to be having trouble with my styles not displaying correctly. Below are the specific lines of code related to it: /* Typography –––––––––––––– ...

Utilizing Ajax and jQuery to verify the initial password input in real-time as the user types

My goal is to create a Change Password page where users can enter their original password and have it instantly checked for correctness without the need for page refresh. I want to display a checkbox image next to the text box when the password is correct. ...

Firebug is highlighting a jQuery error, and I am unsure of how to fix it

I suspect there may be a conflict with jQuery on my website. However, I'm unsure how to utilize firebug for debugging purposes. Whenever I click on the "Calculate Shipping and Handling" link from our cart page, the results fail to display. To test t ...

New Feature in Bootstrap4: Navigation Bar Alignment Shift to the Left

I need help aligning my links to the right side of the page I attempted to use mr-auto but it was not effective <body> <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top mr-auto mt-2 mt-lg-0"> <a class="navbar-brand" hre ...