0

I am facing a problem with on(). Here is my code:

<span class="add" id="id_foo" >add this stuff</span>
$(".add").on('click', function() {
    $.post("/toto.com/add.php", { trainning: this.id }, function() {});
    $(this).html("Remove this stuff");
    $(this).removeClass("add").addClass("remove");
    //alert($(this).attr("class"));-->give the good class
});

$(".remove").on('click', function() {
    //doesn't work
    $.post("/toto.com/remove.php", { trainning: this.id }, function() {});
    $(this).html("add this stuff");
    $(this).removeClass("remove").addClass("add");
});

The selector for the class remove doesn't recognize it whereas when I click on the button with the add class, the class is changing. Do you know what the problem is?

Thank you for your help!

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Gromain
  • 123
  • 6

1 Answers1

5

You need to use delegated event handlers as you're dynamically changing the classes the handlers are attached to. Try this:

$(document).on('click', ".add", function() {
    $.post("/toto.com/add.php", { trainning: this.id });
    $(this).html("Remove this stuff").toggleClass("add remove");    
});

$(document).on('click', ".remove", function() {
    $.post("/toto.com/remove.php", { trainning: this.id });
    $(this).html("add this stuff").toggleClass("remove add");
});

Depending on the location of the script tag this JS code is in you may also need to wrap your code in a document.ready handler. If it's just before the </body> tag it will work fine, if it's in the head, place it inside $(function() { /* your code here */ });

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339