The JQuery code is failing to remove the dynamically added field when the delete icon is clicked

Information: I am currently navigating the world of programming and attempting to build a To-Do List feature. When the create list button is clicked, a dynamically generated div with the class 'wrap' is created. This div contains two nested divs: 1) user input field with the class 'item'. 2) Delete icon with the class 'fa fa-trash'. Each of these wrap divs is housed within a main div with the class "list".

Expected output: My goal is for when the delete icon (class="fa fa-trash") is clicked, the corresponding wrap div associated with it is deleted, effectively removing one list item.

Current output: Regardless of which wrap I try to delete from the list by clicking on the delete icon, it always deletes the oldest wrap that was added initially.

Please advise me on why, upon clicking the delete icon, it does not remove the intended corresponding wrap but rather deletes the oldest wrap that was added.

jQuery Code:

var maxvalue=9; //to restrict the number of list items created
var count = 0; //to count the number of list items created
var listitem = '<div class="item">'; //each user input is contained in this 'item' class
var deleteicon = '<div class="fa fa-trash">'; 
var wrap = '<div class="wrapper" id="dynamic">';//wraps the delete icon & user input within a div

$(document).ready(function(){
$('#createlistbutton').click(function(){
var toAdd = $('input[name=newlistitem]').val(); //user input
        if(count<maxvalue)
        {
          $('.list').append(wrap + listitem +toAdd + '</div>' + deleteicon + '</div>' +'</div>');//adds dynamic item
          count +=1;
        }
        
        else
        {
          alert("No more than 9 lists can be created");
        }
      
    $('.fa.fa-trash').on('click',function(){
      
      $(this).parent().remove();//deletes parent item (wrap) when clicked on delete icon
      count -= 1;
     
    });
      
    });
    
});
-*{  margin:0;
padding:0;
}

body{
  display: flex;
  flex-direction:column;
  font-family: "Times New Roman","Open Sans",sans-serif;
  font-size: 16px;
background-color: #b9d2d4;
background-image: url("https://www.transparenttextures.com/patterns/45-degree-fabric-dark.png");
height:100%;
}

h3{
  color:white;
  margin: 18 0 0 10;
  display: inline-block;
}

.nav-bar{
  height: 10%;
  background-color:#303030;
}
ul{
  list-style-type:none;
  display: inline-block;
  margin:0;
  margin-right:15;
  padding:0;
  float:right;
  overflow:hidden;
}

li{
  float:left;
  margin-top:5;
  
}

li a{
  display:block;
  text-decoration:None;
  padding: 8px;
  color:#ffffff;
  padding: 14px 16px;
  text-align:center;
}

li a:hover{
  text-decoration:underline;
}

footer p{
   margin-top:25px;
   }

footer{
   position:fixed;
   left:0px;
   bottom:0px;
   height:10%;
   width:100%;
   color:#ffffff;
   background:#303030;}
   
.sidepanel{
   width:30%;
   float:left;
   text-align:center;
   height:80%;
   background-color:white;
  }

.inputlist{
  position:relative;
  display:inline-block;
  margin-top:1em;
  margin-bottom: 1em;
   
}

#createlistbutton{
    font-weight:bold;
    color:#ffffff;
    background-color:#303030;
}

form{
  display:inline-block;
}

.item{
  border: 1px solid grey;
  background-color:lightcyan;
  border-radius:15px;
  margin-bottom:1em;
  width=80%;
}

.fa.fa-trash{
  display:inline-block;
}

.list{
  position:inherit;
  width=80%;
  max-height:80%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE>
<html>
<head>
  <title>Python Flask App</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="src-animation.js"></script>
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>

<body>
  <header>
  <div class="nav-bar">
    <h3>PYTHON FLASK APP</h3>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">Sign in</a></li>
      <li><a href="#">Sign up</a></li>
    </ul>
  </div>
  </header>
  <main>
  <div class="sidepanel">
    <div class="inputlist">
    <form name="newlistform">
  <input type="text" name="newlistitem"/>
  </form>
  <button id="createlistbutton">Create List</button>
    </div>
    <br/>
    <div class="list">
  </div>
  </div>
  </main>
  <footer>
    <p>COPYRIGHT &copy 2017 PowerSoft</p>
  </footer>
  </body>
</html>

Sample: http://jsbin.com/magikewuge/edit?html,css,js,output

Answer №1

Check out this solution here

var maxvalue=9; //limits the number of list items created
var count = 0; //keeps track of list items created
var listitem = '<div class="item">'; //each user input is in class item
var deleteicon = '<div class="fa fa-trash">'; 
var wrap = '<div class="wrapper" id="dynamic">';//wraps the delete icon and user input in a div

$(document).ready(function(){
$('#createlistbutton').click(function(){
  var toAdd = $('input[name=newlistitem]').val(); //user input
    if(count<maxvalue) {
    $('.list').append(wrap + listitem +toAdd + '</div>' + deleteicon + '</div>' +'</div>');//add item dynamically
      count +=1;
    } else {
      alert("You can't create more than 9 lists");
    }
  });  
   
  $(document).on('click','.fa.fa-trash', function(){
  $(this).parent().remove();//delete parent item(wrap) when delete icon clicked
    count -= 1;   
  });
    
});
-*{  margin:0;
padding:0;
}

body{
  display: flex;
  flex-direction:column;
  font-family: "Times New Roman","Open Sans",sans-serif;
  font-size: 16px;
 /**background: linear-gradient(45deg, #f06, yellow);**/ 
  background-color: #b9d2d4;
  background-image: url("https://www.transparenttextures.com/patterns/45-degree-fabric-dark.png");
  height:100%;
}

h3{
  color:white;
  margin: 18 0 0 10;
  display: inline-block;
}

.nav-bar{
  height: 10%;
  background-color:#303030;
}
ul{
  list-style-type:none;
  display: inline-block;
  margin:0;
  margin-right:15;
  padding:0;
  float:right;
  overflow:hidden;
}

li{
  float:left;
  margin-top:5;
  
}

li a{
  display:block;
  text-decoration:None;
  padding: 8px;
  color:#ffffff;
   padding: 14px 16px;
  text-align:center;
}

li a:hover{
  text-decoration:underline;
}

footer p{
   margin-top:25px;
   }

footer{
   position:fixed;
   left:0px;
   bottom:0px;
   height:10%;
   width:100%;
   color:#ffffff;
   background:#303030;}
   


.sidepanel{
   width:30%;
   float:left;
   text-align:center;
   height:80%;
   background-color:white;
  }

.inputlist{
  position:relative;
  display:inline-block;
  margin-top:1em;
  margin-bottom: 1em;
   
}

#createlistbutton{
    font-weight:bold;
    color:#ffffff;
    background-color:#303030;
}

form{
  display:inline-block;
}

.item{
  border: 1px solid grey;
  background-color:lightcyan;
  border-radius:15px;
  margin-bottom:1em;
  width=80%;
}

.fa.fa-trash{
  display:inline-block;
}

.list{
  position:inherit;
  width=80%;
  max-height:80%;
}
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<header>
  <div class="nav-bar">
    <h3>PYTHON FLASK APP</h3>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">Sign in</a></li>
      <li><a href="#">Sign up</a></li>
    </ul>
  </div>
  </header>
  <main>
  <div class="sidepanel">
    <div class="inputlist">
    <form name="newlistform">
  <input type="text" name="newlistitem"/>
  </form>
  <button id="createlistbutton">Create List</button>
    </div>
    <br/>
    <div class="list">
  </div>
  </div>
  </main>
  <footer>
    <p>COPYRIGHT &copy 2017 PowerSoft</p>
  </footer>

Your implementation could be functional, but there's a better way to do it.

Since your .fa.fa-trash element is added dynamically, you should delegate an event from document to .fa.fa-trash for deletion.

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

Error encountered when attempting to retrieve JSON data in JavaScript due to being undefined

A snippet of code that reads and writes JSON data is presented below: var info; $(function () { $.getJSON("data.json", function (d) { info = d; }); $('.btn').click(function () { info['c-type'] = $('#c- ...

Press the Relay button to initiate the ASP.NET File Upload functionality

Within an ASP.NET C# website, I have incorporated an input that allows the user to upload a file to the server. To address the limitation of not being able to style an input of type=file, I devised a visually styled div that mirrors the appearance of the i ...

Curved edges, Layering, Content overflow restriction

My design consists of two circular divs with the border-radius property set to its max value. The first circle contains a header div with a unique background-color and overflow:hidden to create the illusion that the top portion of the circle has a differen ...

JSON data utilized in Ajax request

I'm encountering an issue with displaying a value in an input field. Despite having successfully implemented this before, I am struggling to identify where my code may be incorrect. Within my HTML, I have an input field with the id="input" and a butt ...

Show the meta-field mp3 and place it in a lightbox container on the portfolio page

My Current Portfolio Gallery Setup: Currently, my portfolio gallery is displayed in a masonry grid format using the JIG plugin. This grid showcases images from my custom post_type. When clicking on a thumbnail, a lightbox pops up showing the full photo. T ...

Achieve dynamic styling and adjust window size using window.open

My mind is exhausted after days of trying: function prtDiv( o ) { var css = 'body {font:normal 10px Arial;}' ; var wo = window.open('','print','width=600,height=600,resizable=yes'); wo.document.write( '<he ...

Swift code in WKWebView shows increased word spacing in lengthy Arabic texts

Having long Arabic text within <p> tags in my HTML file (loaded by WKWebView) on my app results in unusually large word spacing and unreadable text. In Xcode, the letters in the HTML file appear disconnected. Is there a way to prevent this issue with ...

Tips on sending variables to a PHP script from a JQuery $(document).ready function

I have a chat application in development. I currently have a functioning JQuery code that calls logs.php every second to refresh the chat. $(document).ready( function(e) { $.ajaxSetup({cache:false}); setInterval(function() { ...

The userscript will keep the window open as long as it remains inactive

Hello everyone, I'm excited to join the StackOverflow community and dive into userscripts for the first time! Putting aside any unnecessary details, I'm encountering a small issue with a script I recently created. (function () { $("#enbut"). ...

Python Script for Automated Download of PDF Files within JQueryFileTree

I am working on a project to automatically download PDF files from a website associated with my employer's company. These PDF files are organized within a JQueryFileTree structure. Is there a way for me to download an entire folder along with its cont ...

Lowest value malfunctioning

I have encountered an issue with setting minimum values for 4 things. All 4 things are supposed to have the same minimum value as the first thing, but when moving the slider, everything goes back to normal and works fine. Where could the problem be origina ...

Toggle the visibility of the next unordered list using jQuery

I am experiencing a challenge with toggling the visibility of a ul element in this example. My jQuery script is functioning properly on all elements except for the ul element. $('.dropdown-toggle').on('click', function(event) { $(t ...

The CSS elements are positioned beneath the top border when applying a scale transformation within columns

I have a layout with 4 columns of images that I want to scale on mouse hover using the 'column-count' property. The first column works correctly, but the next three end up positioned under the upper border during the transformation. I've e ...

Unusual patterns appearing in HTML image files

As a beginner in html, please pardon my silly questions and mistakes. I have designed this webpage: <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <style type = text/css> #topbar { ...

I'm having trouble getting my Django for-loop to show the items

Having trouble displaying all the songs on my music streaming website homepage using a carousel. Even though I have around 10 songs in my database, nothing is showing up. How can I fix this issue? This is the HTML code I am using: <div id="All-song ...

Having trouble getting Jquery to work with an Ajax call in the cart drawer. Any suggestions on how to resolve this issue

I used this code to implement a collapsible feature in my Cart Drawer, but it seems to stop functioning after an Ajax call. Any suggestions on how to troubleshoot and fix this issue? Just for context, I included onclick="return false;" in the bu ...

What is a method to adjust the height of a paragraph element in AngularJS based on user interaction?

Is there a way to dynamically adjust the height of a paragraph element in Angular when clicking on a "Show More" button? I want the button text to change to "Show Less" and shrink the paragraph back down when clicked again. What would be the most effective ...

Limiting the scrolling capability within a flex container by using the nowrap

When using flex with nowrap, it appears that the horizontal scroll bar only allows moving to the right while the items on the left remain hidden. To demonstrate this issue, I have created a sample on CodePen: http://codepen.io/anon/pen/QpgvoZ This behavio ...

creating a table with only two td's for formatting

My ultimate goal is to keep my web form code as minimal as possible for easier maintenance. I am currently working on creating a questionnaire and have been using two td elements for this purpose. Here is an example of what the current text structure looks ...

What causes the shift in the position of the div element?

I have been struggling with a problem in my code. Whenever I hover over this element, it rotates as intended but it also changes its position. I can't figure out why this is happening. Can someone please help me debug this? I would greatly appreciate ...