There are two "up" buttons in my html table; above one is from the definition and the bottom one is added by javascript. Please see the codes and jsfiddle demo below:
Table:
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>aaaaa</td>
</tr>
<tr>
<td><input id='btnUp1' type='button' value='up' class='up'/></td>
</tr>
</tbody>
</table>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Javascript:
window.onload = function () {
var tbody = document.getElementById('tbody'),
n, row, cell;
for (n = 0; n < 3; n++) {
row = tbody.insertRow();
cell = row.insertCell();
cell.innerHTML = Math.random();
}
row = tbody.insertRow(2);
cell = row.insertCell();
cell.innerHTML = "<input id='btnUp' type='button' value='up' onclick='NavigateUpDown(this);' />";
$(".up").click(function () { console.log($(this));});
}
$(".up").click(function () { console.log('outsideload:' + $(this));});
function NavigateUpDown(object) {
var count = $('table tr').length; // count gridview rows length
var $row = $(this).parents('tr:first');
console.log($row);
}
Please see the jsfiddle below for demo: http://jsfiddle.net/Balkanlii/apdy34xg/6/
Please open the developer tools of the browser and observe the "console" tab while testing. You will see that when above "up" button is clicked, it returns a context via $(".up").click(function () { console.log($(this));}); in the window.onload. However, It is not triggered when the other "up" button in third row is clicked since it is added by javascript after the window load.
I added NavigateUpDown(object) custom function to receive it, but the context of $row comes "undefined".
Using another line like: $(".up").click(function () { console.log('outsideload:' + $(this));}); did not help as it is not triggered as well.
How can I get the row added by javascript after the page load, in javascript? Do we have something like window.afterload()? Any help would be appreciated.
replace below lines of your code :
with this one :
The
$(document).onwill trigger an event on any dynamic element.try the same on http://jsfiddle.net/o6f705mu/2/