...

View Full Version : jQuery work with changed div



questionable
12-21-2009, 11:16 PM
Hello everyone,

Using:
FF: 3.5
jQuery: latest

Is there a way to make jQuery use code that has been injected into a <div> element.

This code works:

....all the including of Jquery etc goes here...

$("#test").click(function()
{
alert("Hey this Works!");
});

...ending scripts and going to body etc.....
<div id=results><input type=button id=test></div>

This code will not work:

//PHP Code called under specific getjson
$html .= "<input type=button id=test>";
return $html;


....all the including of Jquery etc goes here...
$.getJSON(url, function(data)
{
$("#results").html(data); //this does successfully add input button
});
$("#test").click(function()
{
alert("Why won't this work!");
});
...ending scripts and going to body etc.....
<div id=results></div>

This code successfully adds <input id=test> into <div id=results> but it will not execute because it has been added later. Is there a way to make this work with getJson?

Thanks,

questionable

Fumigator
12-21-2009, 11:58 PM
With the latest jQuery version there is a function called live() which you can use for this very purpose. Here's a similar thread on the subject:

http://codingforums.com/showthread.php?t=180709&highlight=live

tomws
12-22-2009, 12:01 AM
I've had this happen. I think the workaround is to put the new click handler inside the json function so that the event is attached after the appropriate element is inserted.

$.getJSON(url, function(data)
{
$("#results").html(data); //this does successfully add input button
$("#test").click(function()
{
alert("Why won't this work!");
});
});


There's probably a better way to do it, but I think that's how I got mine to work.

tomws
12-22-2009, 12:03 AM
With the latest jQuery version there is a function called live() which you can use for this very purpose.

And there's the better way!

questionable
12-23-2009, 08:48 PM
Works Great!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum