views:

37

answers:

2

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...

+2  A: 

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.

meder
why didn't i think of that...I will use livequery since i have that loaded already...thanks that was the reason!!
Rick
+2  A: 

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.

Matchu
why didn't i think of that...I will use livequery since i have that loaded already...thanks that was the reason!!
Rick
@Rick - note that newer versions of jQuery have `live` built in, and don't require a plugin :)
Matchu
Oh really? Thanks a bunch...I will use live then...When you say newer, as in 1.4.2 and up? or all 1.4+?
Rick
@Rick - it's been around for a while now, [apparently since 1.3](http://api.jquery.com/live/).
Matchu
doh! ok...thanks again!
Rick
@Rick: Please also note that an ID has to be unique. You cannot have have multiple buttons with ID `button`.
Felix Kling
@Felix Kling - I suspect that he's replacing the entire page, so I didn't mention... but yeah, that's worth noting, just in case :)
Matchu