Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a row index in dynamic table via jQuery

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);
    });
like image 759
user3003466 Avatar asked Mar 27 '14 12:03

user3003466


People also ask

How to get dynamic table row value in jQuery?

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).

How to get dynamic row id in jQuery?

showMore', function(event) { var rowindex = $(this). closest('tr'). index(); console. debug('rowindex', rowindex); });

How to dynamically add rows to a table in html?

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.


1 Answers

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.

like image 178
Anoop Joshi P Avatar answered Sep 19 '22 01:09

Anoop Joshi P