Home > Net >  Why does my button not click when I change its id attribute?
Why does my button not click when I change its id attribute?

Time:12-15

I changed the attribute id of a button. The old id #slide_save_button has a light blue color, and the new id #slide_save_button_open has a dark blue color, which changes when it is supposed to. But when I attempt to click the button (by referring to its new id #slide_save_button_open) it won't execute the console.log("clicked"). Why?

$("#catName").on("input", function(){
  if( $("#catName").val().length > 0 ){
    $("#slide_save_button").attr('id', 'slide_save_button_open');
  } else {
    $("#slide_save_button_open").attr('id', 'slide_save_button');
  }
});



$("#slide_save_button_open").on("click", function(){
  console.log("clicked");
});

CodePudding user response:

$("#slide_save_button_open") searches the DOM for an element which has that ID right now. You then add an event handler to it.

When you later change the ID, it doesn't retroactively delete the existing event handlers and rerun the original code to attach new ones.


You can achieve something like that with event delegation where you bind the event handler to an ancestor element and listen for a bubbled event.

$(document).on("click", "#slide_save_button_open", function () { .... });

You could also test for something about the element inside the event handler:

$("#slide_save_button_open").on("input", function(e) {
    if ( $(e.currentTarget).attr('id') === 'catName') {

CodePudding user response:

Base on this https://stackoverflow.com/a/27041899/15924734 it's not ok to change ID attribute. For what you need, you can use addClass(), removeClass() & toggleClass()

  • Related