Morning people. How to make my javascript or jquery works in dynamically generated content.
Basically, i have created web page that generates contents, base on what user clicks on the navigation menu.
The problems i am facing:
Information collected through searching:
jQuery.load() method ignores the script tag that comes together with the that content generated dynamically.
So i try the following:
Example contact.php
<script type="text/javascript">
$(function() {
$("#submitUser").click(function(e) {
var fname = $("#fname").val();
$("#theresult").text(fname);
e.preventDefault();
});
});
<form id="contactForm">
<label for='fname' >First Name</label><br/>
<input id="fname" type="text" name="fname" maxlength="100" />
</form>
<div id="theresult"></div>
When this contact.php is dynamically generated into other page, it doesn't work. When I click "submit" button, console shows no response. seem like the jquery is not exists.
But when I open it alone in browser, it works.
For dynamically generated elements you should delegate the events, you can use the on
method:
$(function() {
$(document).on('click', '#submitUser', function(e) {
var fname = $("#fname").val();
$("#theresult").text(fname);
e.preventDefault();
});
});
live()
method is deprecated.