Amplified
Amplified

Reputation: 1

JQuery issue with ID selectors?

I'm working on a project that allows for text boxes to be added and removed by a user. I've structured my code so that when the general add button is pressed, it creates a text box as well as a delete button for that particular text box.

My problem is that the delete button only works for the first text box, and for the rest of the text box, the JQuery selector doesn't even register that the delete button is being pressed let alone delete it.

Do you have any recommendations? I've included screenshots of code here. HTML code. JQuery code.

Upvotes: 0

Views: 39

Answers (1)

gavgrif
gavgrif

Reputation: 15509

Since the elements are being added dynamically - you need to look at event delegation and use a higher selector for example - if you are appending the elements into a div with the id of 'parentWrapper' - you can then access the click event on the button by delegating it from the parent element. Note that I am assuming that the delete button has a class of 'deleteButton' for this example.

$(document).ready(function(){
  $('#addRow').click(function(){
    var index = $('.added').length+1 ;
    $('#parentWrapper').append('<div class="added">Added Row ' + index + ' <button type="button" class="deleteButton">delete</button></div>')
    })
  
  $('#parentWrapper').on('click','.deleteButton',function(){
    $(this).parent().remove();
  });
});
.added{margin-bottom:15px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type ="button" id="addRow">click to Add a row</button>
<hr/>
<div id="parentWrapper"></div>

Upvotes: 1

Related Questions