user

Jo Micheal

19 Jun 2021

[SOLVED] jQuery .click() not working with auto added buttons

jQuery

I am facing a problem with my page when I add a button automatically using foreach loop with append() function or any way of appending the elements into the page, it doesn't work! using .click() function I am not sure how to figure out this issue

Note: the button do not respond to any command like console.log()

Here is the code of the page 

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Homepage</title>
</head>
<style>
 button { display: block; margin: 10px; }
</style>
<body>
 <div id="hero"> 
 Main section
 <button id="add_btn">Add one more button</button>
 </div>
 <script src="//code.jquery.com/jquery-3.6.0.min.js"></script>
 <script>
 jQuery(document).ready(($) => {
 $("#add_btn").click(() => {
 $("div#hero").append(`<button id="add_more_buttons">add button clicked</button>`);
 }); 
 $("#add_more_buttons").click(() => {
 console.log('This is automatic populated button');
 $("div#hero").append(`<button id="add_more_buttons">add button clicked</button>`);
 });
 });
 </script>
</body>
</html>

Please help if there is any jQuery expert, 
Thanks

Comments

Mohamed Atef

19 Jun 2021

Best Answer

best answer
githubgithubgithub

Hi Jo, 
This issue happened because jQuery doesn't read the new button so you need to use on(); function like 

 $("body").on('click', '#add_more_buttons', () => {
 console.log('This is automatic populated button');
 $("div#hero").append(`<button id="add_more_buttons">add button clicked</button>`);
 }); 

So the entire page should look like 

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Homepage</title>
</head>
<style>
 button { display: block; margin: 10px; }
</style>
<body>
 <div id="hero"> 
 Main section
 <button id="add_btn">Add one more button</button>
 </div>
 <script src="//code.jquery.com/jquery-3.6.0.min.js"></script>
 <script>
 jQuery(document).ready(($) => {
 $("#add_btn").click(() => {
 $("div#hero").append(`<button id="add_more_buttons">add button clicked</button>`);
 }); 
 $("body").on('click', '#add_more_buttons', () => {
 console.log('This is automatic populated button');
 $("div#hero").append(`<button id="add_more_buttons">add button clicked</button>`);
 });
 });
 </script>
</body>
</html>

Replies

Jo Micheal

19 Jun 2021

YEAH! it works, Thank you this is really useful :)

© 2024 Copyrights reserved for web-brackets.com