Nam Thai
Nam Thai

Reputation: 45

jQuery Changing button id doesn't work

I am writing a program where the signin button will be changed to sign out button when the user logged in. The code is as follow:

$("#signin").button().click(function(){
  $("#dialog-user").dialog("open");
});

$.post('php/in.php',function(data){
    $("#signin").attr('id','out');
});

$("#out").button().click(function(){
   alert("clicked out");
});

I have obmitted some code in between, but basically, when the user successfully signed in, the id of #signin button will be changed to #out. However, when I click the new button with id #out, it doesn't show the alert("clicked out") that I specified. It still show the #dialog-user as if the button id is still #signin.

Please help me fix this.

Upvotes: 0

Views: 95

Answers (3)

VoronoiPotato
VoronoiPotato

Reputation: 3173

$("#signin").button().click(function(){
  $("#dialog-user").dialog("open");
});

$.post('php/in.php',function(data){
    $("#signin").attr('id','out');
    $("#out").button().click(function(){
       alert("clicked out");
    });
});

In your example the id is changed after the event is tied, giving nothing to tie the event to. Putting the out button click inside the post function ensures that when we get the data back from the server we change the id and THEN assign the event.

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55740

For such cases you would need to delegate the event to the static ancestor. As events are bound **to the elements and not to the attributes of an element.

Try this approach..

$(document).on('click',"#out",function(){
   alert("clicked out");
});

Or

$(signin static ancestor).on('click',function(e) {
      if(e.target.id === 'signin') {
          $("#dialog-user").dialog("open");  
      }
      else if(e.target.id === 'out') {
           alert("clicked out");
      }
});

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

You need to use event delegation As, #out doesn't exist when you are binding click event i.e on page load

$(document).on('click',"#out",function(){
   alert("clicked out");
});

Upvotes: 3

Related Questions