Reputation: 1921
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?
Upvotes: 0
Views: 731
Reputation: 6464
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
Upvotes: 1
Reputation: 4498
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.
Upvotes: 2
Reputation: 413709
Use "live"
$("#booking-form-time-select").live('change', function() { ... });
Upvotes: 1
Reputation: 630389
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.
Upvotes: 4