开发者

jQuery select "change" event not fired

开发者 https://www.devze.com 2023-01-12 12:13 出处:网络
I have three depending selects. First one, have some values. <select id=\"first\"> <option value=\"1\">v1</option>

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 dynamic开发者_JAVA百科ally loaded content for second select?


try this:

$('#second').change(function(){
    alert('Test')
})


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; 
});


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

(see Why doesn't 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.


as far jquery update its version from jQuery 1.7 its introduce "on" see here http://api.jquery.com/on/ . So if you use following way definately it will call "Change" event.

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

精彩评论

暂无评论...
验证码 换一张
取 消