0

Why my generated button from jquery doesn't have an event?

<input type='button' value='Populate' id='pop'/>
<input type='button' value='Click' id='btn'/>
$('#pop').on('click', function(){
   var clone = $('input[id*=btn]').clone();
   $(this).after(clone);
});

$('#btn').on('click', function(){
   alert('clicked'); 
});

fiddle

Ben Fortune
  • 28,143
  • 10
  • 73
  • 75
Ian
  • 9
  • 4

4 Answers4

2

Id's should be unique. So changed your id btn to class. Use event-delegation. Try this:

$(document).on('click','.btn', function(){
   alert('clicked'); 
});

DEMO

Unknown
  • 18,929
  • 10
  • 62
  • 98
0

You are duplicating id's which is wrong just duplicate class instead.

<input type='button' value='Populate' id='pop'/>
<input type='button' value='Click' id='btn' class="btn"/>


$(document).on('click','.btn',function(){
  alert('clicked'); 
});

Try this(as per your question) :

$(document).on('click','#btn',function(){
  alert('clicked'); 
});

EDIT :

Fiddle link :- http://jsfiddle.net/nLkvejss/

Kartikeya Khosla
  • 18,039
  • 8
  • 39
  • 64
0

try this:

$(document).on('click', "#btn", function(){
   alert('clicked'); 
});
keykay
  • 36
  • 3
  • I think it would be more helpful for the OP and further visitors, when you add some explaination to your intension. – Reporter Aug 29 '14 at 08:48
0

You are creating the cloned button after you have applied event listeners. When you clone() an element ONLY the DOM structure is cloned, the events are not.

Either user Event Delegation or simply pass true to the clone() function to have it clone the events also (as per the spec)

$('#pop').on('click', function(){
   var clone = $('input[id*=btn]').clone(true); // < pass true here
   $(this).after(clone);
});

DEMO: http://jsfiddle.net/rvhhv8sf/3/

P.S. Id's must be unique ;)

Moob
  • 13,593
  • 1
  • 29
  • 45