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.

0

2 Answers 2

5

Use event delegation

$(document).on("click" , "#buttons_insert1 #okcad1" , function() 
{
   alert('hello world');
});
Sign up to request clarification or add additional context in comments.

3 Comments

@downvoters care to comment
Thanks Amit and JqueryKing! But only the JQueryKing answer worked...can u tell me why? Thanks!
Thanks for this. I used the javascript equivalent and it worked perfect. Rafael, I suspect that Amit's answer is assigning the event to the wrong element.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.