Reputation: 215
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>
Upvotes: 1
Views: 60
Reputation: 82231
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();
});
Upvotes: 3