简体   繁体   中英

How to detect empty table when selecting a row in a jQuery Datatable

Giving a simple table like this

<table id="exampleTable" class="table hover nowrap">
   <thead>
      <tr>
         <th>Id</th>
         <th>Name</th>
      </tr>
   </thead></table>

Also, using the jQuery Datatable plugin and making the rows selectable, like in this example . The Javascript goes like this:

var exampleTable = $("#exampleTable").DataTable(
                    {
                        "bDestroy": true,
                        "lengthChange": false,
                        "bPaginate": false
                    });

$('#exampleTable tbody').on( 'click', 'tr', function () {
        if ( $(this).hasClass('selected') ) {
            $(this).removeClass('selected');
        }
        else {
            $('#exampleTable tr.selected').removeClass('selected');
            $(this).addClass('selected');
        }
    } );

So, when the table is empty, it shows a selectable row which says something like:

No data available in table

How to detect the table is empty and not allow selection on that kind of "message rows"?

Here is a fiddle with the code.

you can check if there is td with the class dataTables_empty like this:

$('#exampleTable tbody').on( 'click', 'tr', function () {
        if ( $(this).hasClass('selected')) {
            $(this).removeClass('selected');
        }
        else if(! $(this).find('td.dataTables_empty').length){
            $('#exampleTable').DataTable().rows().nodes().each(function(){
               $(this).removeClass('selected');
            });
            $(this).addClass('selected');
        }
    } );

You can use the - .row().data() method to see if there is data. if this returns undefined, you can disable selection of the row.

i also think this would be an ideal solution instead of dom traversal which is more expensive. what do you guys think ?

below is the updated fiddle. you can comment the tbody from the html to test it.

Let me know if this helps.

Modified Fiddle

inside your click method, add before everything

if($('#exampleTable tbody tr td').length == 1){
      return;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM