I have a table which refreshes upon keyup of input elements in a form. Upon keyup, I am refreshing the table data by first removing all existing rows, and then dynically adding new table rows. Each table row includes a link to another page. On initial page load, the link works correctly on the first click; but on subsequent table refreshes, the link does not fire until the second click.
Many other SO posts have recommended using the "on" method, however, this does not work in this case. The problem here seems to be caused by the jQuery "remove" method. When I comment out the line below, the link always works correctly on the first click.
$("#myTable").find("tr:not(:first)").remove();
I also tried using "detach" instead of "remove", but am running into some circular logic, as I'm trying to detach dynamically created rows that don't exist yet and then add them back later.
Here's the relevant code snippet:
$("input, select, #circles-slider").on("keyup change slidestop", function(event) {
function searchSuccess(data, textStatus, jqXHR) {
$(document).ready(function() {
$("#myTable").find('tr:not(:first)').remove();
for (var i = 0; i < data.length; i++) {
var convertedData = JSON.stringify(data);
var str = jQuery.param(params);
$('#myTable tr:last').after(
"<tr>\
<td data-label='Rate' class = 'main-rate'>" + data[i][0].toFixed(3) + "%</td>\
<td data-label='APR'>" + data[i][2].toFixed(3) + "%</td>\
<td data-label='Payment'>$" + data[i][3].toFixed(2) + "</td>\
<td data-label='Program'>" + data[i][7] + "</td>\
<td data-label='Points'>" + data[i][8].toFixed(3) + "</td>\
<td data-label='Closing Costs'>$" + data[i][9].toFixed(2) + " </td>\
<td data-label='Apply' id = 'tree'><a class = \'target\' href = \'/application\/?" + str + "'>Apply Now</a></td>\
</tr>");
}
});
}
});
// testing use of "on" does not work
$("#myTable").on("click", "a", function(){
alert("Test click");
});
<table id="myTable">
<caption>Loan Program options and interest rate table</caption>
<tr id="header_row">
<th>Rate</th>
<th>APR</th>
<th>Payment</th>
<th>Program</th>
<th>Points</th>
<th>Closing Costs</th>
</tr>
</table>
Full code is here: https://jsfiddle.net/shanif/kqLkaax7/ Thanks for the help!