Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery selector not finding elements when it loaded by ajax

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?

like image 767
Mahmoud.Eskandari Avatar asked Dec 12 '22 07:12

Mahmoud.Eskandari


1 Answers

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.

like image 184
Satpal Avatar answered Mar 15 '23 08:03

Satpal