-1

I am creating a button using javascipt like below:

 "<div class='row'><button id='rkeys'>Related<button></div></div>"

  $('#search_results').append(html_result)

And below that I have the functions which is waiting for a click event on '#rkeys' id, but nothing happens when I press that button.

 related_keys = ->
   console.log('click')
 $('#rkeys').on 'click', related_keys

What can I do to make this work.

John
  • 634
  • 8
  • 29

2 Answers2

4

Try this:

related_keys = ->
   console.log('click')
 $('#search_results').on 'click','button', related_keys
Kiran
  • 20,167
  • 11
  • 67
  • 99
3

You need event delegation:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$('#search_results').on('click','#rkeys',function(){
    //click event code.
}); 
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125