Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Second page does not work with Codes in the first page

I have a main page that I have loaded another page on it via ajax when document is ready ,also I have a button that when I click It I shows an alert and, I have that button in the second page too. but when i click on it in that page that code does not work ? how can i solve this problem ?

because I do not want to repeat js codes on the second page ?

here is my first page code :

first page code:

<html>
<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
<div class="captcha" style="border:1px solid red;">
</div>
<div class="details1">cccc</div>
<script>
$(document).ready(function(e) {
$(".captcha").load("/secondpage.htm");
$(".details1").click( function()
{
 alert('button clicked');
}
);

});
</script>
</body>
</html>

and this is my second page that I have loaded into div with classname captcha:

second page code:

<html>
<head>
</head>
<body>
 <section class="details1"> Details </section>
</body>
</html>
like image 669
inaz Avatar asked Dec 21 '17 07:12

inaz


1 Answers

When you need to create new elements on-the-fly, you can not use standard click etc. events. Dynamically created elements are not born with the same event handlers as the existing elements. You have to dynamically attach event handlers to newly created elements.

Replace 'click' with 'on'.

 $("body").on("click", ".details1", function(){
 alert('button clicked');
});
like image 126
newman Avatar answered Oct 22 '22 08:10

newman