Gleydson S. Tavares Gleydson S. Tavares - 1 month ago 8
Javascript Question

Multiple buttons with same class don't work

I created multiple buttons with the same class from a list of words.

var words = $(this).val().split(' ');
$.each(words, function(i, v) {
if ($.trim(v) !== '') {
html += "<button class='wordbtn'>"+ v +"</button>" + " "
}
});

$("p").html(html);


The buttons are displayed in my view, but when I click the button does not work.

$(".wordbtn").click(function(){
console.log('clicked')
})


When I inspect my code buttons are shown, but when I view the source code the buttons are not displayed.
If I insert a pre button to test, it works.

<p><button class='wordbtn'>Test</button><p>

Answer

try replace the click event for your button with:

$(document).on("click", ".wordbtn", function(event){
    console.log('clicked');
});

this click event will fired even with a new added button