简体   繁体   中英

Check if datatables is empty after table is fully loaded jQuery

After doing some research on this issue trying to find a solution (unfortunately to no avail) I decided that it might be best to post my problem. I currently have a Datatable containing asset information on a view and I'm trying to prevent a user from continuing change an option on a select field until an asset is added to the asset table.

Listed below is my assets datatable code in my .js file under the document.ready function

assets = $('#assets').dataTable({
    sAjaxSource: "http://" + window.location.hostname + "/request/get-request-assets/?id=" + $('#id').val(),
    fnDrawCallback: function (oSettings) {
        setIncompleteTD();
        enableRequestStatus();
    },
    scrollY: '185px',
    scrollCollapse: true,
    paging: false,
    aaSorting: [[1, 'asc']],
    bPaginate: false,
    bFilter: false,
    bLengthChange: false,
    bAutoWidth: false,
    bInfo: false,
    aoColumns: [
        {sWidth: '35px', bSortable: false},
        {sWidth: '40px'},
        {},
        {},
        {},
        {},
        {},
        {sWidth: '80px'}
    ],
    language: {
        sLoadingRecords: '',
        sEmptyTable: 'This request has no asset records.',
        sInfoEmpty: ''
    }

I've found table.fnSettings().aoData.length===0 as a means to check if a table is empty. However, after stepping through the code (via Chrome debugger) it seems Datatables (at least in my case) calls the function before the table is fully generated...

I have this code below

assetPresent = (assets.fnSettings().aoData.length===0) ? false : true;
console.log(assetPresent);

in my document.ready function after $('#assets').dataTable() function (if this matters). AssetPresent will be used as a flag to toggle the status select box. Unfortunately before I can utilize that...

console.log(assetPresent);

Seems to always be set to false even if there are clearly records in the table, and...

assetPresent = (assets.fnSettings().aoData.length===0) ? false : true;

Tends to be ignored...

I'm curious to see if table.fnSettings().aoData.length===0 might not be the best option. Thank you in advance.

您是否尝试过table.data()。length吗?

you can try this

var table = $('#assets').DataTable();

if ( ! table.data().any() ) {
   alert( 'Empty table' );
}

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