Jumabek Alikhanov
Jumabek Alikhanov

Reputation: 2383

jQuery doesn't catch the event

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

Upvotes: 0

Views: 130

Answers (1)

Alex
Alex

Reputation: 11255

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.

Upvotes: 1

Related Questions