After appending a button on Html document the jQuery event associated with it not working ?
For example:
$("#mydiv").append('<a href="#" id="mybutton">X</a>');//this is button appending
$("#mybutton").click(function(){
alert("hello");
});
After appending a button on Html document the jQuery event associated with it not working ?
For example:
$("#mydiv").append('<a href="#" id="mybutton">X</a>');//this is button appending
$("#mybutton").click(function(){
alert("hello");
});
Assuming you call the .click()
method on #mybutton
before it is actually appended to #mydiv
, you need to use .on()
as the button doesn't exist when you attach the event handler:
$('#mydiv').on('click','#mybutton',function(){
alert('hello');
});
Should work...
Why don't you set the click
inside the append
?
This way you wouldn't need to concern about the element being added or not to the document's flow, since you'd be setting the event callback on the actual DOM element variable:
$("#mydiv").append(
$('<a href="#" id="mybutton">X</a>').click(function() {
alert("hello");
})
);