Mahmoud.Eskandari
Mahmoud.Eskandari

Reputation: 1478

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?

Upvotes: 4

Views: 12546

Answers (3)

Satpal
Satpal

Reputation: 133403

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.

Upvotes: 13

Mahmoud.Eskandari
Mahmoud.Eskandari

Reputation: 1478

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

it's looks good!

Upvotes: 1

Jain
Jain

Reputation: 1249

You can also use live event

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

Note : live event depericated in v1.9

Upvotes: 0

Related Questions