Unable to delete dynamically added content using jQuery

I use jQuery to allow users to dynamically add and remove form fields, but it doesn't work as expected.

It works great when deleting the first field (which is hardcoded in the HTML markup), but it will not allow me to delete any of the fields that were added dynamically.

Here is my jQuery code:

$("#addDog").click(function(event) { event.preventDefault(); var doglist = <?php echo "'" . $javadogs . "'"; ?>; var newdog = '<div><select name="resDog[]" class="select">' + doglist + '</select><input type="text" class="shortinput" name="resResult[]" size="20" value="" /><a href="#" class="deleteDog"><img src="/admin/images/delete.png" alt="Remove dog" /></a></div>'; $(this).parent().before(newdog); }); $(".deleteDog").click(function(event) { event.preventDefault(); $(this).parent().remove(); }); 

I tried using the jQuery .on() function, but that didn't work either.

+1
source share
1 answer

Here, how do you want to use on

 $(document).on("click", ".deleteDog", function(e) { e.preventDefault(); $(this).parent().remove(); }); 

Ideally, all these deleteDog buttons will be placed in some kind of container. If all these buttons should be in a div with the identifier foo , you would more effectively configure the following events:

 $("#foo").on("click", ".deleteDog", function(e) { e.preventDefault(); $(this).parent().remove(); }); 

Now, instead of every click anywhere in the document being checked, only those clicks that appear before #foo .


I assume that you initially tried using on as follows:

 $(".deleteDog").on("click", function(e) { e.preventDefault(); $(this).parent().remove(); }); 

This is functionally identical:

 $(".deleteDog").bind("click", function(e) { e.preventDefault(); $(this).parent().remove(); }); 

Omitting a selector parameter such as this creates a direct-bound event only for events that will be associated with elements that match the .deleteDog selector at time on .

Using the selector type in my source code makes it a delegated event - jQuery will listen for all clicks, and if they come from an element with the deleteDog class, the function will be Fire.

+6
source

Source: https://habr.com/ru/post/905927/


All Articles