Why do jquery events not work when creating an object via Javascript innerHTML?

Asked

Viewed 113 times

2

I’m making the following code:

var botoesTela = "<button id='okcad' class='botao_padrao botao_ok' value='OK' onclick=''> <img src='/php/Images/OK.png' alt='OK' /> OK </button>";
divBotoes.innerHTML = divBotoes.innerHTML + botoesTela;

but when I try to catch the click button in HTML page

$("#okcad").click(function() 

he doesn’t do anything...?

  • Is there an error in the console? When is the click function bind performed? Before or after the Document button is inserted?

  • 1

    It may be the order in which things are done. In that case you would need delegate the event.

1 answer

3

Two reasons (code errors) that could lead to this problem:

#1

Problem: The element is created afterward that this jQuery be read.
Solution: You need to delegate the event.
New code: $(document).on('click', "#okcad", function(){

#2

Problem: Duplicated Ids if you’re adding buttons like this several times.
Solution: Use classes instead of Ids or dynamically generate Ids to be unique.
New code: $(".botao_padrao.botao_ok").click(function(){


You can combine the two ideas and use: $(document).on('click', '.botao_ok', function(){

Browser other questions tagged

You are not signed in. Login or sign up in order to post.