raduenea Posted September 7, 2021 Share Posted September 7, 2021 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 Quote Link to comment https://forums.phpfreaks.com/topic/313682-add-event-to-an-element-created-with-javascript/ Share on other sites More sharing options...
requinix Posted September 7, 2021 Share Posted September 7, 2021 Where are you using table_body? Quote Link to comment https://forums.phpfreaks.com/topic/313682-add-event-to-an-element-created-with-javascript/#findComment-1589725 Share on other sites More sharing options...
raduenea Posted September 7, 2021 Author Share Posted September 7, 2021 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> Quote Link to comment https://forums.phpfreaks.com/topic/313682-add-event-to-an-element-created-with-javascript/#findComment-1589729 Share on other sites More sharing options...
Solution kicken Posted September 8, 2021 Solution Share Posted September 8, 2021 You need to use a delegated event which involves Adding the event to some parent element that will always exist and Adding a selector argument when calling the .on method. $('#tableDiv').on('click', '#edit', function(){ alert('Hi!'); }); Quote Link to comment https://forums.phpfreaks.com/topic/313682-add-event-to-an-element-created-with-javascript/#findComment-1589737 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.