Reputation: 24212
From the documentation
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
I'm using jQuery 1.7.1
This works, for static elements and dynamically loaded elements:
$("input").live("change", function () { alert("hello"); });
This doesn't work, not even for static elements:
$("document").on("change", "input", function () { alert("hello"); });
What am I missing?
Upvotes: 2
Views: 691
Reputation: 13461
Write it like
$(document).on("change", "input", function () { alert("hello"); });
You can replace document
with any closer parent element
which will always exist in DOM
for better performance. Like
$('#closest_static_container_id').on("change", "input", function () {
alert("hello");
});
if you use $("document")
jQuery will search for a node/tag
named as document
like <document>
and wont find anything as document
is actually an object
.
But you could use $("body")
as body
is a node/element of DOM
.
Upvotes: 8
Reputation: 150253
Change:
$("document").on(...)
To:
$(document).on("change", "input", function () { alert("hello"); });
document
is an object (a property of window
), not a node type.
$("document").on(...)
Is looking for <document>
elements in the document
object, like:
<document>
And as you probably got by now, there is none...
Anyway the best practice with on
is to use the closest static element to the dynamic added elements Something like:
<div id='container-div-id'>
<input /> ... this will be added later.
</div>
$('#container-div-id').on("change", "input", function () {
alert("hello");
});
Upvotes: 4
Reputation: 69905
document
is an object and you are using it as a string. So jQuery
will try to use it as a css selector and it will not find anything to attach the event handler.
Try this.
$(document).on("change", "input", function () { alert("hello"); });
Upvotes: 2