0

I assign new id to a button. this is my code

$("#update").click(function(){
    $("#update").attr('id', 'cancel');
});

and i after changing the id. i want to use it to be functional again in jquery to revert it back to update. having this code.

$("#cancel").click(function(){
    $("#cancel").attr('id', 'update');
});

my problem is, after it changed the id attribute when i click the cancel nothing happens. what is the problem of my code.? thank you in advance.

Barmar
  • 741,623
  • 53
  • 500
  • 612
doy619
  • 11
  • 4

2 Answers2

0

Use event delegation using jQuery.on, it will automatically bind the click event as the id is changed. You need to use static parent to delegate the event you can use document as well if you can not use static parent.

$("#staticParentId").on("click", "#update", function(){
   $("#update).attr('id', 'cancel');
});

$("#staticParentId").on("click", "#cancel", function(){
    $("#cancel").attr('id', 'update');
});

Beside the above solution I do not see any real reason to change the id of a html element. You can toggle the behavior of html element use the same click handler.

Live Demo

$("#update").click(function(){
    if(this.value == "update")
    {
        this.value = "cancel";
        //more action
    } 
    else   
    {
        this.value = "update";
        //more action
    }     
});
Adil
  • 146,340
  • 25
  • 209
  • 204
0

You need to read about event delegation

In your code, you are binding event when element does not exist in DOM.

Try this:

var BODY = $('body');//any parent selector
BODY.on('click', "#update", function() {
  $("#update").attr('id', 'cancel');
});
BODY.on('click', "#cancel", function() {
  $("#cancel").attr('id', 'update');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Community
  • 1
  • 1
Rayon
  • 36,219
  • 4
  • 49
  • 76