1

I have a button <button class="open" id="1">Open</button>

if I click on the button I wanted the button to change into <button class="close" id="1">Close</button>

I made some script for it

Here is the script:

$(".open").click(function(){
    $ths=$(this);
    var id=$(this).val();
    $.ajax({
        type:"POST",
        url:"someurl",
        dataType: "html",
        data:id,
        success:function(res){
            $thd.html("Open");
            $ths.toggleClass("open close");
        }
    })
});

$(".close").click(function(){
    $ths=$(this);
    var id=$ths.val();
    $.ajax({
        type:"POST",
        url:"someurl",
        dataType: "html",
        data:id,
        success:function(res){
            $ths.html("Close");
            $ths.toggleClass("close open");
        }
    })
});

When I try it, On first click it changed the <button class="open" id="1">Open</button> into <button class="close" id="1">Close</button>

On second click I hope it changed back to this <button class="open" id="1">Open</button>

But it didn't changed to what I want. It changed to this <button class="open" id="1">Close</button> It only changed the class, the close text to open not.

Can someone explain why it is not working? and also how to make that button change class and its text, oh yeah also is this problem has a name?.

Thx in advance for answering!

Calvin
  • 605
  • 10
  • 26

1 Answers1

1

$(".close") will find element .close in the DOM and will bind events. As you are changing the class of the element dynamically, element is not there in the DOM when jQuery tries to find it.

Use Event Delegation, Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. Use .on() instead of click

$(document).on("click", ".open", function() {
  $ths = $(this);
  var id = $(this).val();
  $.ajax({
    type: "POST",
    url: "someurl",
    dataType: "html",
    data: id,
    success: function(res) {
      $ths.html("Open"); //You had a typo here!
      $ths.toggleClass("open close");
    }
  })
});

$(document).on("click", ".close", function() {
  $ths = $(this);
  var id = $ths.val();
  $.ajax({
    type: "POST",
    url: "someurl",
    dataType: "html",
    data: id,
    success: function(res) {
      $ths.html("Close");
      $ths.toggleClass("close open");
    }
  })
});
Rayon
  • 36,219
  • 4
  • 49
  • 76