views:

151

answers:

3

I have some content from server using $.ajax() function. I try to replace some element with this data and then manipulate it. Here is code:

$.ajax({
 type: "GET",
 url: "smpl.php",
 success: function(servmsg){
  $('#panelInfo').replaceWith('<p>' + servmsg + '</p>');
 }
});

response from server is:

<select id="years">
    <option>2008</option>
    <option>2009</option>
</select>

when I try some event on it, it's doing nothing, for ex:

$('#years').change(function() { //or .click()
    //do something
});
A: 

Hello.
The event binding code should be inside the 'success' function, so it will run after #years is added to the page. Otherwise, jquery is looking for #years and cannot find it, and no binding is made.

Kobi
+3  A: 

You need to change your code to:

$.ajax({
    type: "GET",
    url: "smpl.php",
    success: function(servmsg){
        $('#panelInfo').replaceWith('<p>' + servmsg + '</p>');
        $('#years').change(function() { //or .click()
            //do something
        });
    }
});

Alternately, you could keep your original ajax call code, and use livequery like so:

$('#years').livequery('change', function() { //or .click()
    //do something
});

Then when you inserted the #years block, it'd have the change event automatically registered.

David
A: 

If you can use jquery 1.3 (release today) then look into the new .live() method.

redsquare