1

I search around the web but cant do this work..

Im creating a dialog in a js.file . In this js i have a function that creates a button, but with innerHTML...

    var divButtons = document.getElementById('buttons_insert1');    
    var buttons_insert = "<button id='okcad' class='button_ok' value='' > <img src='/php/Images/OK.png' alt='OK' /> OK </button>";
    divButtons.innerHTML = divButtons.innerHTML + buttons_insert;

and in the index.html i have a jquery function to get the click event.

$("#okcad1").click(function() 
{
   alert('hello world');
}

but this is not working..the event dont fire...

Someone could help me?

Regards!

Rafael S.

2 Answers2

5

Use event delegation

$(document).on("click" , "#buttons_insert1 #okcad1" , function() 
{
   alert('hello world');
});
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
2

You need event-delegation, since you're appending it after DOM has been loaded. For that use jQuery.on

$("#buttons_insert1").on('click', '#okcad1', function() {
   alert('hello world');
}

Just click will bind the event to the elements which were present in the DOM when the code got executed, so you need the technique of event-delegation.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95