1

I am using jQuery to create an html button with id "cancel". On my actual page, clicking my #edit button will successfully create my cancel button. However I am unable to then use this cancel button for future jQuery actions. Is there a solution to this?

$(document).ready(function() {
  $("#edit").click(function() {
    $("#button").html("<input id='cancel' type='button' value='cancel' />");
  });
  
  // Here I want to access my new button
  
  $("#cancel").click(function() {
    ('p').hide();  
  });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='button'><input id='edit' type='button' value=edit /></span>
<p>Hide me upon cancel</p>

1

1 Answer 1

3

Yes. event delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

You are also missing jquery selector while targeting p elements.

 $("#button").on('click','#cancel',function() {
   $('p').hide();  
 });
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, exactly what I needed. And for catching the typo :)
@Tortooga: glad it helps
As a bit of a follow up question... what if I want clicking "cancel" to cause the button to revert back to a functioning "edit" button? I tried to store the contents of the original #button as a variable, and then reassign #button after clicking cancel. But this puts me back at my original issue where the button cannot be selected by jQuery.
for that you will need to delegate #edit event. exactly the same way done for cancel button

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.