-2

I faced this problem while doing some exercises. Can't select recently added button number two, and cant call alert method

$('#but').click(function() {
  $('#but').after('<button id="but2">Кнопка 2</button');
});
$('#but2').click(function() {
  alert('something');
});

Having only this HTML code:

<button id="but">Кнопка 1</button>
Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
Roman Sarder
  • 99
  • 1
  • 8

3 Answers3

1

Your htmlString is lacking a > on its closing tag:

.after('<button id="but2">Кнопка 2</button');
                                          ^

And use event delegation for dynamic elements:

$(document).on('click','#but2',function(){
   alert('something');
});
Rax Weber
  • 3,730
  • 19
  • 30
0

You have dynamically added button. And direct click event will not work.

Try this:

$(document).on('click','#but2',function(){
   alert('something');
});
Kinshuk Lahiri
  • 1,468
  • 10
  • 23
0

you can use this to select the second button

$('#but').eq(2).click(function() {
  alert('something');
});
Kasnady
  • 2,249
  • 3
  • 25
  • 34