views:

463

answers:

3

So here is my code:

$(document).ready( function() {
$('#form').bind('change', function(){
    $.ajax({
    type: 'get',
    url: 'api.php',
    data: 'task=getdirs&formname='+$('#form').attr('value'),
    dataType: "text",
    success: function (html){
        $('#chdir').html(html);
        $('#chdir select').bind('change', getDirs());
        }
    });
});
function getDirs(){
}})

#form here a select element, the ajax call returns me a peace of html with new select element.
It works nice: in the #chdir div I get new dropdown element. But there also event inside success fires one time. Then this event not working at all.
What can I do to make new created select working the same way as first?

A: 

Instead of using bind, try using .live. You'll need the latest version of jQuery to do that.

marcgg
A: 

If I understand you correctly, the problem is with the event not working with your dynamically created select element.

If so, the solution is simple...try this:

$('#form').live('change', function()...
Alex
This will make sure that the event gets bound every time.
Alex
+3  A: 

You are invoking the getDirs function directly on the bind method call, you should only do it if this function returns another function, but I think that's not the case.

Change:

$('#chdir select').bind('change', getDirs());

To:

$('#chdir select').bind('change', getDirs);

Or if you are using jQuery 1.4+, you can bind the change event with the live method only once, and you will not need to re-bind the event after that:

$(document).ready(function () {
  $('#chdir select').live('change', getDirs);
});
CMS