m2j
m2j

Reputation: 1160

dataTable row into hyperlink error

I'm new to deal with dataTable. I tried to convert the row into href using below code:

"fnRowCallback": function( row, data ) {
    $('tr', row).html('<a href="userDet/' + data[3] + '"><td>' +data[0]+ '</td><td>' +data[1]+ '</td><td>' +data[2]+ '</td></a>');
    return row;
},

which is not working, but while convert href to single column. It's working fine.

"fnRowCallback": function( row, data ) {
    $('td:eq(1)', row).html('<a href="userDet/' + data[3] + '"><td>' +data[0]+ '</td></a>');
    return row;
},

what i'm doing wrong?

Edit

My html is:

            <table id="myTable" class="table table-hover">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Door No</th>
                        <th>Address</th>
                        <th style="display: none;">Account ID</th>
                    </tr>
                </thead>
                <tbody>

                </tbody>
            </table> 

my Jquery is:

    var oTable = jQuery('#myTable').dataTable({
    processing: true,
    serverSide: true,
    "bDestroy": true,
    "pageLength": 6,
    "ajax": '/userDetails?query='+query+'',
    "type":'get',
    "fnRowCallback": function( row, data ) {
                $('td:eq(1)', row).on('click',function(){
                  window.location = 'userDet/' + data[3] ;
                });
            },

    "columnDefs": [
        {
            "targets": [ 3 ],
            "visible": false,
            "searchable": true
        }
    ]        

    });

Upvotes: 0

Views: 329

Answers (1)

Rajshekar Reddy
Rajshekar Reddy

Reputation: 19007

You need to follow the table HTML structure.. table, tbody, tr, td.... If this structure breaks then your CSS will break and DataTables features might break too..

Your approach will break the table structure as you are attempting to put a a tag directly under tr. tr should always have td as it's child.

Solution: Use data-* attribute to store the navigation URL in the tr tag and on click of this tr load the page you want just like a anchor tag click..

Here is sample:

"fnRowCallback": function( row, data ) {
    $('tr', row).attr('data-navigate-url','userDet/' + data[3]);
    return row;
},

This will set the attributes on your TR tags..

Add click event handler to these tr tags

$("#yourTable").on('click','tr',function(){
    window.location = $(this).data('navigate-url');
});

Upvotes: 1

Related Questions