I have a script doing a mysql query and populate a table using
$('#results').html(returnData);
The mysql results contains data that should be clickable and reloaded into the same table (replacing the previous query).
Simplifying and boiling it down, the following code does not work:
<head>
<script>
$(document).ready(function() {
$('.a').click(function() {
$('#results').html('THIS IS VALUE FROM LINK A <a href="#" class="b">B</a>');
});
$('.b').click(function() {
$('#results').html('THIS IS VALUE FROM LINK B');
});
});
</script>
</head>
<body>
<div id="results">THIS WILL BE REPLACED WITH VALUE FROM LINK A OR B</div><BR>
<a href="#" class="a">LINK A</a><BR>
<a href="#" class="b">LINK B</a>
If I click LINK A OR B the div id="results" is populated OK, but when I place the same link inside one of the .html results returned from click functions the link is not working and the div id”results” is not reloading itself.
So my questions are; why would that not work? and what would be the best way to reload the same table based on what you click inside the table that is already passed from .html()? I do not want to pass the clicked value on to a new page.
UPDATE:
This will work using .on()
<script>
$(document).ready(function(){
$('body').on('click', '.a', function() {
$('#results').html('THIS IS VALUE FROM LINK A <a href="#" class="b">B</a>');
});
$('body').on('click', '.b', function() {
$('#results').html('THIS IS VALUE FROM LINK B');
});
});
</script>
</head>
<body>
<div id="results">THIS WILL BE REPLACED WITH VALUE FROM LINK A OR B</div><BR>
<a href="#" class="a">LINK A</a><BR>
<a href="#" class="b">LINK B</a>
To elaborate on Abhilash’s comment, the reason your click event isn’t firing is due to the event listener only being attached to elements which currently exist in the DOM at the time onReady is executed.
.live() was introduced in older versions of jQuery – now deprecated in favor of .on() – to combat this problem. It allows you to attach events to a static element like body, and when the click event propagates up to the body it checks the original target element which triggered the event against your .on() selector, if they match it executes the handler.