0

For a web based project, I am using jQuery. In one part of the code, there is data that gets dynamically added to the screen on the client side based on the activity of other users connected to the server. I want to write a code that will allow me to execute a function when a client clicks on the data.

To elaborate a little bit, there is a list which shows which members are online. When a new client connects, his name is added to the list and all other users can see on their screen that he is online. When another user clicks on his name, he sends a message request.

This is the relevant jQuery code:

$('#inc').append("<br><i onclick='accept()'>"+data.plr+"<i><br>")

And the accept function is defined under this block which is within another function, so like

function a(){
     $('#inc')....
}
function accept(){
    //...
}

However, when the code runs I get an error which says accept() is not defined

How do I solve this problem?

RishiC
  • 768
  • 1
  • 10
  • 34

4 Answers4

1

Maybe you can do it in that way...

$('#inc').append("<br><i>"+data.plr+"<i><br>")
$('#inc i:last-child').click(accept);

I did a small CodePen to let you see the code in action https://codesandbox.io/embed/frosty-jang-fvk3j

RishiC
  • 768
  • 1
  • 10
  • 34
  • This did work. However, the `onclick='accept()'` still gives an error saying it is not defined. So I removed that part only, and it worked smoothly. So the code is now `$('#inc').append("
    "+data.plr+"
    ")` `$('#inc i:last-child').click(accept);` Thanks a lot for the help
    – RishiC Jul 19 '19 at 08:14
1

I've always done it this way. I find this easier.

$('#inc').append("<br><i class="child">"+data.plr+"<i><br>")

$('.child').on("click",function(){
//your code here
});
Hadji
  • 96
  • 6
1

You can do it with this way as well :

jQuery(function(){
      click_link = $('<a class="" href="#">Click here</a>');
      click_link .bind("click", function(){
        alert('DO something');
      });

      $('.your_dom').append(click_link );
    });
Ravi Koradia
  • 879
  • 7
  • 13
1

Write it using jQuery methods:

var $i = $('<i>').text(data.plr).click(function(event) {
    //handle here onClick event
}); //or if you have the function already declared just write .click(accept);

$('#inc').append('<br />', $i, '<br />');

https://api.jquery.com/click/