I am trying to detect an event in a jQuery appended element.
- How do you do this,
- and/or why isn’t this working:
Here’s a simplified snippet of what I’ve tried. The input field fires after clicking “click me.” After clicking on the input, the alert isn’t firing – other events on this appended input don’t fire either. 🙁
The following’s in script tags:
$(document).ready(function(){
$(".clickme").click(function(){$(".extra").append('write: <input type="text" class="writesomething" />');});
$("input").click(function(){alert("clicked")});
});
The following’s in the body:
<a href="#" onclick="return false" class="clickme">click me</a>
<div class="extra"></div>
Do it like this:
Try it out: http://jsfiddle.net/eDDeZ/1/
You’re creating the new element, assigning the click handler directly to it, appending it to
.extra, then adding thewrite:text before it.No need for
.live()this way.EDIT:
Another option is to use
.delegate()which will be more efficient that.live()since it is focused on a particular container instead of the entire page.Try it out: http://jsfiddle.net/eDDeZ/2/