I have a div whose content gets dynamically generated from innerHTML and I cant seem to target those elements using jQuery for validation, Eg This is the page:
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
</head>
<body>
<span id="alert1">Alert1</span>
<input type="button" value="Click Me" id="button1" />
<div id="empty"></div>
</body>
</html>
and this is the js code:
<script type = "text/javascript">
$(document).ready(function() {
$('#button1').click(function() {
var html = "uname <input type='text' id='uname'><br />password <input type='text' id='password'><br /><span id='alert'>Alert</span>";
$('#empty').html(html);
});
$('#alert').click(function() {
alert('Alert');
});
$('#alert1').click(function() {
alert('Alert1');
});
});
</script>
The alert for the span with id alert1 works but for id alert which is set using innerHTML or .html() does not work so how to fix this?
Thank you in advance
The problem here is that when you write like this..
.. it will only create events handlers for elements that exist when you execute the code. It won’t create event handlers for future elements even if they have the same jQuery selector (“#element” in this case).
What you need to do is bind with
.on(event, selector, function)on a parent element, as the events “bubble up” the hierarchy. That way you can handle future events from the specified selector. Personally I would do it like this: