1

I've a jquery script to remove articles from a shopping cart:

<script type="text/javascript">
    $(document).ready(function(){ 
        $(".deleteLink").click(function(e) { 
            e.preventDefault();
            var id = $(this).attr('data-id');
            $.ajax({
                type: 'POST',
                url: 'delete.php',
                data: "id=" +id
            })
            .done(function(data){
                alert("Deleted.");
                var url="basket.php";
                $("#warenkorb").load(" #warenkorb > *");
            })
            .fail(function() {
                alert("Error");
            }); 
            return false;  
        });
    });
</script>

This works when I enter the page and click on a Delete-Link. When I click on the second link it does not work anymore. I have to reload the page. Then I can delete again exactly once.

The Link looks like this:

<a class="deleteLink" data-id="$id" href="#">Delete</a>

Could anybody imagine what the problem could be?

Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26
Harry1747
  • 11
  • 1
  • 1
    Use $(".deleteLink").on.("click", function(e) { ... } because you change the content of your shopping cart dynamically. – Gerard Dec 04 '19 at 07:42
  • Thanks for your help. When I use $(".deleteLink").on.("click", function(e) { ... unfortunately nothing happens when I click on the link (not even the first time) – Harry1747 Dec 04 '19 at 07:50
  • 1
    Use `$(document).on("click", ".deleteLink", function(e) { ... }` – Roy Bogado Dec 04 '19 at 08:00
  • have you check console log if any occur in it? – Jinesh Dec 04 '19 at 08:02
  • When I remove $("#warenkorb").load(" #warenkorb > *"); the items are deleted correctly, but the shopping cart is not updated od course. – Harry1747 Dec 04 '19 at 08:11
  • @Roy That was the solution. Thank you very much! – Harry1747 Dec 04 '19 at 08:13
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – peeebeee Dec 04 '19 at 11:46

1 Answers1

1

Use $(document).on("click", ".deleteLink", function(e) { ... }

Documentation: $(document).on()

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()

Roy Bogado
  • 4,299
  • 1
  • 15
  • 31