-2

I have a code like this:

...
<script>
function myfunction(result) {
    $(".dyn").prop("innerHTML",result);
}
</script>
...
<table class="dyn">
</table>
<script>
    $.post('some_ajax_page',some_value,myfunction);
    $(".myeditable").on(blur,myfunction2);
</script>
...

The POST executes correctly and gets the content of the table, which is displayed correctly, and it is like this:

...
<tr><td class="myeditable">...</td></tr>
...

But the TD doesn't have a listener set for blur, even when the listener intends to be set after the POST has returned and its function executed.

Why doesn't the listener get set?

rrk
  • 15,677
  • 4
  • 29
  • 45
Envite
  • 321
  • 2
  • 6
  • 16
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – JJJ Feb 15 '16 at 12:23
  • 1
    Or, in this case, attach the event listener in `myfunction()`. Ajax is asynchronous, you have to wait for the request to complete. – JJJ Feb 15 '16 at 12:24
  • `.blur` event on `td` how is it focussed? what do you have in`myfunction2`? – Jai Feb 15 '16 at 12:30
  • @Jai focused by mouse event, myfunction2 is a call to handle the edition of the td (which is, by the way, contenteditable="true"). – Envite Feb 15 '16 at 12:33

1 Answers1

0

You need to add the event listener after you insert the html on the callback.

<script>
function myfunction(result)
{
    $(".dyn").prop("innerHTML",result);
    $(".myeditable").on(blur,myfunction2);
}
</script>

Remember the call back function on $.post() will only execute when the data is received, asynchronously, so the line after $.post() will actually execute before the callback.

  • Not a good idea to bind event like this, if you run the function again there will be two bound events. XD – Jai Feb 15 '16 at 12:33
  • @Jai good point. will not happen in my case, but as a general answer your point is very important. – Envite Feb 15 '16 at 12:34