Skip to content
Advertisement

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

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");
});

Advertisement

Answer

Your approach fails because the code looks for the element at that moment in time. When it finds it, it binds it. The code does not keep looking for elements.

To do it your way, you would need to use event delegation.

$("#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');
  }
});

$(document).on("click", "#slide_save_button_open", function() {
  console.log("clicked");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
  <label for="catName">Name:</label>
  <input id="catName" name="catName"/>
  <button type="button" id="slide_save_button" name="slide_save_button">Run</button>
</form>

Now changing the id is not really the best solution. You probably should just take a “validation” approach and use a variable to hold the state or you can use a class.

const btn = $("#slide_save_button");

$("#catName").on("input", function() {
  btn.toggleClass("open", $("#catName").val().length > 0);
});

btn.on("click", function() {
  if (btn.hasClass("open")) {
    console.log("clicked");
  } else {
    console.log("need to fill in");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
  <label for="catName">Name:</label>
  <input id="catName" name="catName" />
  <button type="button" id="slide_save_button" name="slide_save_button">Run</button>
</form>

But you could just use HTML5 validation

const form = $("#myForm");
form.on("submit", function (evt) {
  evt.preventDefault();
  console.log("clicked");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
  <label for="catName">Name:</label>
  <input id="catName" name="catName" required/>
  <button type="submit" id="slide_save_button" name="slide_save_button">Run</button>
</form>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement