jquery selector not finding elements when it loaded by ajax

10,689

Solution 1

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

As you are loading content by ajax.

You need to use Event Delegation. You have to use .on() using delegated-events approach.

Use

$(document).on('change','#myid', function(){
   alert('OK!');
});

Ideally you should replace document with closest static container.

Solution 2

$('#myid').live('change', function(){
    //and scope from $(this) here
    $(this).parents().find('.class:first').attr('id');
});

it's looks good!

Share:
10,689

Related videos on Youtube

Mahmoud.Eskandari
Author by

Mahmoud.Eskandari

Updated on September 15, 2022

Comments

  • Mahmoud.Eskandari
    Mahmoud.Eskandari over 1 year

    None of jQuery selectors working on loaded elements from server through Ajax requests, but it works good in normal mode.

    $('#myid').change(function(){
      alert('OK!');
    });
    
    <select id="myid" >
     <option>1</option>
    </select>
    

    How to fix this issue?