Reputation:
I have a page dynamically generated with javascript and it contains several input fields and a button. When I click the button, nothing happens...Is it because it is a javascript object and not a "real" dom object? If so, is there a way to interact with the object?
I just wrote a simple alert to see if the button is even working.
jQuery("#button").click(function() {
alert("yes it's working");
});
On first page load this works...I believe on first page load it is PHP generated and when I click to another section, this same button will show up BUT the page does not refresh so this leads me to believe when I click on to another section, it is dynamically re-generated with JS.
Now if I click the button, nothing happens...no errors or no alerts...
Upvotes: 2
Views: 168
Reputation: 85812
I think I get what you're saying.
When you run jQuery('#button')
, it searches for the elements then and there. The event is attached to the button itself, not to the query string #button
.
jQuery does, however, offer the behavior you want.
jQuery('#button').live('click', function () { /* on click event */ });
live
attaches to the query string, not the elements, so it will apply to any #button
ever generated in the future.
Upvotes: 2
Reputation: 186662
You need to use .live
because at the point in time when you assign the handler the element doesn't exist.
$('#button').live('click', function() {
});
You should also look into delegate if you're doing this with multiple elements for efficiency purposes.
Upvotes: 3