tags:

views:

12

answers:

2

Hi all,

I am using jQuery's $.get() to load some content to a div whose id=results :

$.get('dynamicpage.php',
function(data) {
 $('#results').html(data);
});

The returned content has got a select in it :

<select id="myselect"><option value="10">10</option></select>

I have already put a listener for the change on this select :

$('#myselect').change(function() {
    alert("changed");
});

However, this alert in the listener never gets fired.

Do I need to do something special to access elements in the loaded div from jQuery ?

Thank you !

+1  A: 

The issue is that, at the point you added the change event handler to the select, that select didn't exist (or the one that did exist has since been replaced).

You should use the jQuery live() function instead, which will maintain the event binding even if the element is added later.

JacobM
indeed :)Many thanks !
oimoim
+1  A: 

Try this:

$.get('dynamicpage.php',
   function(data) {
       $(data).find('#myselect').change(function() {
            alert("changed");
        })
        .end().appendTo('#results');
});

Here you .find() the #myselect and attach the change event.

Or this:

$('#results').delegate('#myselect', 'change', function() {
            alert("changed");
        });

$.get('dynamicpage.php',
   function(data) {
       $('#results').append(data);
});

Here you attach a .delegate() handler to #results that will listen for the change event on #myselect. This is a little more efficient than .live().

patrick dw