-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,015
  • 11
  • 37
  • 46
Roman Sarder
  • 89
  • 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,661
  • 17
  • 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,445
  • 9
  • 21
0

you can use this to select the second button

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