Search code examples
javascriptjqueryjquery-steps

JQuery button click does not work


I have a JQuery FIddle properly running. It uses a JQUERY Steps PlugIn . Now if you run JQuery FIddle in the last step you will find three button "Save", "Previous" and "Finish". If I click on Save button I want to show an alert saying "you have been clicked". If you scroll to the bottom of the HTML Section in the JSFiddle you will find below code.

Code working fine:

// on Save button click
    $(".actions").on("click",".saveBtn",function(){
      alert("You have been clicked!");
    });
  });

Code not working:

 $( ".saveBtn" ).click(function() {
      alert("You have been clicked");
    });

Question: Why does the second code snippet not work?


Solution

  • A short story about events:

    Since your button with class .saveBtn is created dynamically it doesn't get initialized at document load. But in order to bind events to elements they normally need to be initialized on startup. Your button however gets created when all events are bound to elements already. So you need to do something called event delegation. This means that you listen to a specific event in the entire document for example. When the event fires you look up which element fired the event. This way even dynamically created elements can be selected. A common method for this is the following:

    $(document).on('click', '.saveBtn', function(){
      alert("Dynamic button clicked. Hurray!");
    });
    

    This way you are telling the entire document to register click events and compare the source of the event with your selector, in this case .saveBtn.