I use jquery to dynamic create table content in page, how can I get the row number index of this dynamic table? In the following code, when I click the "show more" link, I use index function in following code, but it not work. How to solve this issue? Thanks.
$.getJSON(JsonURL,
function(data){
$.each(data, function(index, item){
var obj = item;
books.push(book);
});
for (var i = 0; i<obj.length; i++) {
var tr=$('<tr></tr>');
$('<td>'+ obj[i].name +'</td>').appendTo(tr);
$('<td>'+ obj[i].category +'</td>').appendTo(tr);
$('<td><a class=\'showMore\' href=#>'+ 'show more' +'</a></td>').appendTo(tr);
tr.appendTo('#tableBody');
};
});
$('a .showMore').on('click', function(event) {
var rowindex = $(this).parent().parent().children().index($(this).parent);
console.debug('rowindex', rowindex);
});
jQuery: code to get TD text value on button click. text() method we get the TD value (table cell value). So our code to get table td text value looks like as written below. $(document). ready(function(){ // code to read selected table row cell data (values).
showMore', function(event) { var rowindex = $(this). closest('tr'). index(); console. debug('rowindex', rowindex); });
For adding dynamic row in table, we have used insertRow() method. This method will insert a row at position specified by the index arguement. Also for removing row, we have used deleteRow() method. Note that for inserting dynamic row, we have to created cells by using row.
you should use event delegation for that
$(document).on('click',".showMore", function(event) {
var rowindex = $(this).parents("tr").index();
console.debug('rowindex', rowindex);
});
Event delegation allows you to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With