4

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?

Mahmoud.Eskandari
  • 1,460
  • 3
  • 20
  • 32
  • 1
    it's not a bug, you just need to use the appropriate selector for your situation. For clicks for example, `on` or `live` or `delegate` will listen for clicks through AJAX loads where `click` will not – scrowler Feb 09 '14 at 19:58
  • possible duplicate of [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by-event-hand) – Felix Kling Feb 09 '14 at 20:21
  • I search About this And not find it. it's not duplicate question...your link just like my question – Mahmoud.Eskandari Feb 09 '14 at 20:23

3 Answers3

12

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.

Satpal
  • 132,252
  • 13
  • 159
  • 168
1
$('#myid').live('change', function(){
    //and scope from $(this) here
    $(this).parents().find('.class:first').attr('id');
});

it's looks good!

Mahmoud.Eskandari
  • 1,460
  • 3
  • 20
  • 32
0

You can also use live event

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

Note : live event depericated in v1.9

Jain
  • 1,209
  • 10
  • 16