views:

126

answers:

4

Hi, I have come into a bit of a problem. I am dynamically updating dropdown lists using JQuery and PHP. I am using the following JQuery code to run a PHP page and insert the results into the page:

$("#booking-form-area").change(function()
  {
  ajax_availabletimes();
  })

function ajax_availabletimes(){
  var venue_val=$("#booking-form-venue").val();
  var people_val=$("#booking-form-people").val();
  $("#booking-form-time-select-ajax").load("/booking/times-dropdown.php", {venueUID : venue_val, people : people_val}, function(){
  })
}

In times-dropdown.php I am basically doing some lookups and returning some html in the form of:

<select class="small" id="booking-form-time-select"><option value="-1">Select Time...</option><option value="12:00">12:00pm</option><option value="12:30">12:30pm</option><option value="13:00">1:00pm</option></select>

This is put into the #booking-form-time-select-ajax div.

However if I now try selecting something in the dropdown here it should fire the function (this works before a dropdown has been selected and $("#booking-form-offer-select-ajax").load has replaced the code):

$("#booking-form-time-select").change(function()
  {
  ajax_offerdropdown();
  })

I can only presume once JQuery has replaced the code in booking-form-time-select then it can't use selectors? Any idea how to fix this? I have been reading up about $(data) function but it's quite confusing and not sure it is what I am looking for?

+4  A: 

Use .live() in this case:

$("#booking-form-time-select").live('change', function(){
  ajax_offerdropdown();
});

This puts an event listener up at the DOM level that won't get erased as the element is replaced.

Nick Craver
Awesome, many thanks to all of you, that has driven me mad all weekend!
bateman_ap
It's starting to seem to me that there are about 5 different things that account for 80% of all the hair pulled from new jQuery programmers' heads.
Pointy
+1  A: 

Use "live"

 $("#booking-form-time-select").live('change', function() { ... });
Pointy
+2  A: 

The .change() listener is added at page load, so when you replace a DOM element, the attached .change() listener gets removed. Try using live(), which will automagically add the listener to any DOM elements that get added after initial page load.

Pickle
+1  A: 

as alternative why do not replace only the options while leaving intact the tag select ? i mean just return

Select Time...12:00pm12:30pm1:00pm

from php code and update the select options using $('#booking-form-time-select').html(options); this way your handler is preserved

luca