I would like to add a button to the current page using html()-function.
This button needs to be selectable, and alert(‘click’) when it is clicked. This seems impossible.
Look at this code
<script type="text/javascript">
$(document).ready(function(){
$('a').click(function(event){
$('div').html('<form method="post" action=""><input type="submit" /></form>');
event.preventDefault();
});
$(':submit').click(function(event){
event.preventDefault();
alert('click');
});
});
</script>
<a href="#">Click here to add button</a>
<div>Here</div>
What I want is to be able to click <a href="#">Click here to add button</a>. Jquery uses $('div').html('<form method="post" action=""><input type="submit" /></form>'); to replace the div with a submit button.
What I want to happen is for the submit button click to trigger alert('click'). This doesnt happen though.
Any ideas why?
Thanks,
Marius
Use event delegation, either with
liveordelegate. E.g.:livewill:Thus event handlers attached to elements which have been injected into the DOM programmatically will work irrespective of when said handlers were attached.