0

I am trying to use following code but my jquery selection doesn't catch the click event

$('#addLevel').on('click', function() {
    var div = '<div class="form-inline">';
    var addButton = '<button  class="btn btn-success addItems" onclick="alert()" type="button">Добавить</button>';
    div += addButton;
    div += '</div>';
    $('#levels').append(div);
});
//I assume following code is not working but why?
$('.addItems').eq(0).on('click', function() {
    alert('clicked');
});

Thank you

Dhaval Panchal
  • 648
  • 6
  • 26
Jumabek Alikhanov
  • 2,305
  • 3
  • 21
  • 21
  • when i use onclick="alert()", it works – Jumabek Alikhanov Jun 27 '14 at 10:56
  • 1
    make sure the script is executed on dom ready and the `#addLevel` element is present in the dom at that time – Arun P Johny Jun 27 '14 at 10:57
  • 4
    Use [event delegation](http://learn.jquery.com/events/event-delegation/): `$(document).on('click', '.addItems:first', ...`. Otherwise the button doesn't exist when you attempt to attach the click handler to it. – blgt Jun 27 '14 at 10:58
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – JJJ Jun 27 '14 at 11:00

1 Answers1

1

Then you try to add handler to .addItems there is no such DOM nodes. As @blgt said you must use event delegation:

$(document).on('click', '.addItems:first', function() {
    alert('clicked');
});

P.S. Better use any parent node of .addItems:first instead of document.

Alex
  • 11,115
  • 12
  • 51
  • 64