CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript frameworks (http://www.codingforums.com/forumdisplay.php?f=62)
-   -   jQuery work with changed div (http://www.codingforums.com/showthread.php?t=185054)

questionable 12-21-2009 10:16 PM

jQuery work with changed div
 
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:
Code:

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

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

Code:

....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 10: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.p...highlight=live

tomws 12-21-2009 11:01 PM

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

$.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-21-2009 11:03 PM

Quote:

Originally Posted by Fumigator (Post 902074)
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 07:48 PM

Works Great!
 
Works Great!


All times are GMT +1. The time now is 02:57 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.