Superdrac
Superdrac

Reputation: 1208

.change() function on dom element generated after load

i'm trying to catch a change() on a select which is added after the dom generation but i can't success. Here is a sample code:

HTML:

<div class="test" id="divTest"></div>

jQuery:

$('#divTest').click(function(){ $(this).parent().append("<select id='testSel'><option value='f'>F</option><option value='F'>D</option></select>");});

$('#testSel').change(function(){
    alert('change');
});

I want to see the alert when i change the value in the select..

And here is a fiddle. http://jsfiddle.net/T8J8p/3/

Upvotes: 2

Views: 2116

Answers (5)

James Donnelly
James Donnelly

Reputation: 128791

Two problems:

  1. Your select element's ID is #testS not #testSel.1
  2. You need to use event delegation for this, through jQuery's on() method:
$('body').on('change', '#testS', function(){
    alert('change');
});

JSFiddle demo.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.


1. This related to original JSFiddle featured in the question (available here). The question has since been edited.

Upvotes: 5

miguel-svq
miguel-svq

Reputation: 2176

$('#divTest').click(function(){
  $(this).parent().append("<select id='testS'><option value='f'>F</option><option value='F'>D</option></select>");
  $('#testS').change(function(){alert('change');});
});

You can't bid to something that does not exist yet, so bind it after the click, inside the function. And there was a typo in the selector #testS vs #testSel

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You have to bind event using event delegation as the element is added to the DOM after the DOM loaded:

$(document).on('change','#testSel',function(){
    alert('change');
});

See Details HERE

Upvotes: 0

Rashmin Javiya
Rashmin Javiya

Reputation: 5222

Try this,

$('body').on("change", "#testSel", function(){
    alert('change');
})

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

You need event delegation dynamically added DOM::

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$(document).on('change','#testS',function(){
 alert('change');
});

Demo

Upvotes: 3

Related Questions