Jump to content

Add event to an element created with javascript


Go to solution Solved by kicken,

Recommended Posts

Hello,

Plese help me with this situation.

For exemple I want to show alert when I click on EDIT link.

Now when I click on EDIT nothings happen.

Here's the code:

<script>

    function loadData() {
        var table_body = '<table border="1"  id="table">';
        table_body += "<tr>";
        table_body += "<td>Some text</td>";

        table_body += "<td><a href='#' id='edit'>EDIT</a></td>";
        table_body += "</tr>";
        table_body += "</table>";
    }

        $(document).ready(function () {
            loadData();
            $("#edit").on("click", function () {
                alert('hohoho');
            });
        });
</script>  

Thanks

2 hours ago, requinix said:

Where are you using table_body?

<script>

    function loadData() {
        var table_body = '<table border="1"  id="table">';
        table_body += "<tr>";
        table_body += "<td>Some text</td>";

        table_body += "<td><a href='#' id='edit'>EDIT</a></td>";
        table_body += "</tr>";
        table_body += "</table>";
      
      	$("#tableDiv").html(table_body);
    }

        $(document).ready(function () {
            loadData();
            $("#edit").on("click", function () {
                alert('hohoho');
            });
        });
</script>  

	<p id="tableDiv"></p>

 

  • Solution

You need to use a delegated event which involves

  1. Adding the event to some parent element that will always exist and
  2. Adding a selector argument when calling the .on method.
$('#tableDiv').on('click', '#edit', function(){
   alert('Hi!');
});

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.