views:

50

answers:

4

I have three depending selects. First one, have some values.

<select id="first">
<option value="1">v1</option>
<option value="2">v2</option>
</select>

Second and third are blank:

<select id="second"></select>
<select id="third"></select>

I want to populate blank selects via ajax requests. So I do:

jQuery('body').delegate('#first','change',function(){
jQuery.ajax(
{
'type':'GET',
'data':{'changed':$('#first').val()},
'url':'myURL1',
'cache':false,
'success':function(html){jQuery("#second").html(html)}});
return false;
});

So it works fine. The second select is populated, but... no 'change' event is fired for select 'second'. To get this event, I have wrote:

   $(document).ready(function()
    {
        $('#second').live("change", function()
        {
            alert('test');
        });
    });

But no alert 'test' is visible. How to catch this 'change' event for dynamically loaded content for second select?

+1  A: 

try this:

$('#second').change(function(){
    alert('Test')
})
André Gadonski
Tried, same result :(
x17az
A: 

Have you tried adding the assignment of the change event inside of the success callback of the AJAX?

Aaron Hathaway
A: 

What version of jQuery are you using? Anything prior to 1.4.x didn't support live events for change.

(see http://stackoverflow.com/questions/1267072/why-doesnt-jquery-1-3-3-live-support-all-events)

Here is the API for it http://api.jquery.com/live/

You can see in the caveats:

In jQuery 1.3.x only the following JavaScript events (in addition to custom events) could be bound with .live(): click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, and mouseup.

James Wiseman
Changed to .change(function() { }) with no result
x17az
A: 

Because the #second element just exists don't have to use the delegate and live functions

$('#first').change(function(){ 
  $.ajax( 
  { 
    'type':'GET', 
    'data':{'changed':$('#first').val()}, 
    'url':'myURL1', 
    'cache':false, 
    'success':function(html){
      $("#second").html(html);
     }
   }); 
   return false; 
});

$('#second').live("change", function()   
{   
  alert('test');   
}); 

if you want to do the alert right after populating the second select, then include it in your callback function of the $.ajax()

$('#first').change(function(){ 
  $.ajax( 
  { 
    'type':'GET', 
    'data':{'changed':$('#first').val()}, 
    'url':'myURL1', 
    'cache':false, 
    'success':function(html){
      $("#second").html(html);
      $("#second").change();
     }
   }); 
   return false; 
});
Dave
Thank you. It helps :)
x17az