Having an issue with jQuery where trying to append a remove button to a list results in the

Looking to create a dynamic list where users can easily add new items by clicking a button. As each item is added, a corresponding remove button should also be displayed.

The issue I'm facing is that every time a new item is added, an extra close button is appended, causing a cascading effect like this:

.
..
...
....
.....
......

Below is the Javascript code I'm using:

 $('a').on('click', function(e){
   e.preventDefault();
   var a = $(this).closest('form').find('ol, li').last().html();
   console.log(a);
    var closeButton = "<a href='#' class='remove-upgrade-field'>Remove</a>" 
    $('<li>' + a + closeButton + '</li>' ).appendTo('ol');

 });

 $('.remove-upgrade-field').live('click', function(e){
   e.preventDefault();
   $(this).closest('li').remove();
 });

Check out this live demo on JSFiddle

Answer №1

Transform your code using:

JavaScript

$('a').on('click', function(event){
    event.preventDefault();
    var content = $(this).closest('form').find('ol, li').last().children().html()
    console.log(content);
    var closeBtn;
    closeBtn = "<a href='#' class='remove-upgrade-field'>Remove</a>" 
    $('<li>' + content + closeBtn + '</li>' ).appendTo('ol');

});

$('.remove-upgrade-field').live('click', function(event){
    event.preventDefault();
    $(this).closest('li').remove();
});

Check out the fiddle

Answer №2

The reason is that each time you click on var closebutton, it appends the following code:

"<a href='#' class='remove-upgrade-field'>Remove</a>" 
    $('<li>' + a + closeButton + '</li>' ).appendTo('ol');

For more information, try logging the output of closebutton in the console.

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

Babel had trouble transpiling due to an unexpected token while working with Bootstrap 4 and Codekit

Currently attempting to minify and transpile Bootstrap 4 using CodeKit3. However, encountering the following error: Babel: Failed to Transpile: SyntaxError: /bootstrap/carousel.js: Unexpected token (219:8) 217 | _getConfig(config) { 218 | ...

I require the use of XSL to verify the href value of links and modify it if needed, without altering any other attributes

The code mentioned above performs the following tasks: Locates links Checks if it is a fully pathed link or an email link If yes, no action is taken. If no, it checks for a # to determine if it is an anchor If yes, no action is taken. If no, it adds the d ...

Executing a controller method in AngularJS when redirecting a page

I am currently working on an app using Cordova/Phonegap, Ionic, and AngularJS. One challenge I am facing is trying to call a method from a controller inside my app when redirecting to another HTML page (secondPage.html). This particular method (secondMetho ...

`Changing the output of a jQuery .load function`

I've created a webpage that pulls content from an article, but I'm looking to display only the first 100 words of the article. Currently, my page successfully loads the article using this code: $(function(){ $('#startOfArticle').l ...

Interpolation problem with AngularJS translation service

I've successfully implemented a ternary operator in my HTML: {{ qp.QP_TRANSFERS === '1' ? qp.QP_TRANSFER_TYPE_NAME + ' transfer' : 'No transfer' }} In addition, I am utilizing a translation service with JSON objects. He ...

Attempting to format a number using a computed property and .toLocaleString() fails to execute

I am facing an issue with the formatting of a number displayed in a <p></p> element. The number is coming from a range input element that is bound to an amount data property using v-model. Even though I have a computed property to format the nu ...

PHP Warning: Attempt to access undefined variable

Whenever I try to insert a new record into my HTML, I keep encountering errors. I'm unsure if it's due to incorrect code on my end or if the issue lies with inserting the records. <?php $servername = "localhost"; $dbusername = "r ...

Issues with premature execution of Angular JS code have been observed at times

Currently facing an issue with my code where the updateProduct() function call is happening before the forEach loop begins running on about 1 out of every 10 page loads. Not sure why this is occurring or how to solve it. Any insights on what might be causi ...

The website is showing up blank when accessed on mobile devices

One of the websites we recently worked on used to appear correctly on iPhone and Blackberry, but now it shows up as blank on both devices. Interestingly, the site still displays as usual on iPad even though we never created a specific mobile version for ...

Interactive image map with hover effects and external image swapping placed beyond the container

I've encountered a problem with a responsive image map and rollovers. Using Matt Stow's responsive image jQuery plugin ensures that coordinates are responsive, and clicking on an area brings up Lightview as expected. However, the issue arises whe ...

How to obtain the current URL of an iframe?

After coming across what seems to be a similar question, I still have to ask for clarification because I couldn't find a clear answer. Allow me to elaborate on my project, I am working on an online store where we offer two types of products, The fi ...

Issue with processing multiple submit buttons using ajax and php

I am relatively new to working with PHP and AJAX. Currently, I have two submit buttons in my HTML form and I am using AJAX's serialize() method to pass values to a PHP file. The issue I am facing is that serialize() is unable to differentiate between ...

AngularJS - Directives cannot pass their class name into inner template

My goal is to create a directive that can apply a class name conditionally. However, I encountered an issue where the code only works if the class name is hardcoded into the class attribute. When I attempt to use it with any expression, it fails to work. ...

Mastering the nav-item class in Bootstrap 4 for optimal navigation functionality

When I look at the examples in the documentation, I have noticed that the .nav-item class is not doing anything when I inspect my nav bar (the class doesn't show up in the console)... Although this isn't a major issue as I can apply my own style ...

Tips for managing submitted data to a server in express?

In the process of sending a post request from my index.js to app.js upon a click event, I have the following code snippet: var data = { name: "Sarah", age: "21" }; var xhr = new XMLHttpRequest(); xhr.open("POST", "/", true); xhr.setRequestHe ...

The browser automatically adds a backslash escape character to a JavaScript object

When attempting to send an MQTT message to a topic from my angular app, the message needs to be in a specific syntax: { "Message": "hello" //the space after : is mandatory } However, upon sending the message in the correct format, the browser aut ...

Failure of AJAX to transmit variable to PHP script

I am relatively new to PHP and currently working on the dashboard page of a website where an administrator can view all existing admins. Each admin's row has a button that is supposed to check their privileges, such as access to article editing and cl ...

Combining Custom JQuery with Nested JQuery UI Tabs

Currently, I am using the Slate Wordpress theme which includes shortcodes for tabs powered by jquery.tabs.min.js. However, I encountered a problem when trying to nest tabs using the theme's shortcodes. To solve this issue, I decided to create my own ...

Various browsers do not support JSON data fetching through JQuery

On my HTML page, I am extracting data from a static JSON file that has been renamed as a .js file and stored on a local server at 10.211.20.62:8080/case1/county_json.js The code I have written works fine in Internet Explorer versions 6, 7, and 8, but it d ...

Exploring the world of jQuery: Toggling radio buttons with variables on click

On the right side, there is a table of data that initially contains certain values, but can be modified using radio buttons and a slider on the left. If you select the first radio button for the "pay in full" option, it will increase the estimated discoun ...