Quantcast
Channel: Recent Discussions — DataTables forums
Viewing all 82216 articles
Browse latest View live

fixedHeader doesn't scroll horizontal

$
0
0

I have a datatable that uses fixedHeader and "scrollX: true". No Y scroll.

The only problem is that if you scroll down, the header is fixed but it does not follow the horizontal scroll but stays in place.

Is there a quick fix for this?

Thanks!

Regards,


Styling with bootstrap 4

$
0
0

Hi,
Here is attached a screenshot of my table using Bootstrap 4.
Why is it so bulky? The cells have so much padding in them, and thoses grid lines are not what I want.
This table doesn't look like the one in the bootstrap 4 example page.

I use these files :
bootstrap 4.1.0 css
dataTables.bootstrap4.min.css
jquery.dataTables-1.10.16.min.js
dataTables.bootstrap4.min.js

The table have these classes :

<

table class="table display no-footer table-striped table-bordered" id="table1">

And I use this js code :
$(document).ready(function() {
var table = $('#table1').DataTable();

        ...
    });

Thanks
Michael

Cannot access editor from the table when scroller is initialized

$
0
0

I've been using the datatables editor with pagination without any issues. I now want to use the scroller instead of the pagination, but this has cause several problems.

The most predominant being that I can no longer access the editor when I select a row and click edit.

I've made a stand alone example of this issue. I've posted the code to github:
https://github.com/diegoapardo/datatables

And a live example can be accessed here:
datatables-example.herokuapp.com/test.html

I'm not sure what the problem might be, but I am using require.js, which might be causing issues on how the library is being loaded.

Further, in my code, I can't access the editor from the table when the scroller is initialized.
I can get the table by assigning var table = $('.AdminTable').DataTable();, but the editor function returns undefined when I try to assign var editor = table.editor();.

Any insight or suggestions would be appreciated.

Hi All! I am new to datatables. I am using this to display results from ajax call.

$
0
0

On a single page, I have user form and the result section. User fills the details and submit. On this, datatable is displayed. This works perfectly fine. But when user updates anything on the form and submits it, I am trying to destroy datatable and recreate it. Doing this, i am getting the error - clientWidth of undefined. Below is the code -

function CBResults(response){
    var dataArray = response.data;
    
    
    
    if ($.fn.DataTable.isDataTable("#thetable")) {
        $('#thetable').dataTable();
        $('#thetable').DataTable().clear().destroy();
        
        
    }
    var html = '<tbody>';
    for(var i = 0; i < dataArray.length; i++)
        html += '<tr><td></td></tr>';  // code to populate columns of the table
    
    html += '</tbody>';
    
    
        $('#thetable thead').first().after(html);

        $('#thetable').DataTable( {
            retrieve: true,          
            dom: 'Blfrtip',
            scrollY: "300px",
            responsive: true,
            scrollX:        true,
            scrollCollapse: true,
            columnDefs: [ {
                targets: [4,5,6,7,8,9,10,11],
                render: $.fn.dataTable.render.ellipsis(10)
            } ], 
            buttons: [
                'colvis','copy', 'csv', 'excel', 'pdf'  
            ],
            fixedColumns:   {
                leftColumns: 2
            },
            
             "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
        } );
}

Let me know what I am doing wrong and how can I correct it? Appreciate quick reply on this.

Uncaught ReferenceError: jQuery is not defined at jquery.dataTables.js:56

$
0
0

Hello,

When I include the references for DataTable:

<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.13/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.13/js/jquery.dataTables.js"></script>

I get an error in the Chrome console:

Uncaught referenceError: jQuery is not defined, at line 56 of jquery.dataTables.js

Line 56 in jquery.dataTables.js is:

factory( jQuery, window, document );

This error doesn't come up if I remove the references.

Is this a known bug? Is there a way to fix it? Does it have anything to do with jquery.dataTables.js clashing with something in my application?

Thanks

Filtered Columns, width 100%, and scrollX

$
0
0

Hello,

I'm hoping this is a pretty simple question.

Can I use the code below to filter my data AND keep my data to 100% of screen size. As my table has 15 columns, when I turn off scrolling it causes the rows to wrap which causes the filtering to stop working.

I'm looking to filter my data and have the table shrink the columns to fit the screen. I've tried quite a few things, but I can't believe I'm the only person to want to combine these two. Maybe I use a different filter function?

the code:

$(document).ready(function() { $('#IN_Ship').DataTable( { "paging": false, initComplete: function () { this.api().columns().every( function () { var column = this; var select = $('') .appendTo( $(column.footer()).empty() ) .on( 'change', function () { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search( val ? '^'+val+'$' : '', true, false ) .draw(); } ); column.data().unique().sort().each( function ( d, j ) { select.append( ''+d+'' ) } ); } ); } } ); } );

Any help would be appreciated.

If I need to I'll build a full test site, I can. I'm using CSS and all scripts locally. I'll just need to get all the links set back up for the native dataTables location.

Thanks for your time and attention.

Sample implementation of serverside processing in C# MVC, EF with paging/sorting/searching

$
0
0

I have seen people asking a few times how to use datatables serverside with MVC and EF with paging sorting and searching etc. I had some code lying around so I thought its time to give back and share a simple implementation.

Unfortunately I don't have time right now to create a sample solution for download so I just hacked out the code and pasted it in here as a guide.

For the dynamic searching (where clause) you will need linqkit for the predicate building.

First map the datatable inbound JSON requests to classes

Start - JSon class sent from Datatables

public class DataTableAjaxPostModel
{
    // properties are not capital due to json mapping
    public int draw { get; set; }
    public int start { get; set; }
    public int length { get; set; }
    public List<Column> columns { get; set; }
    public Search search { get; set; }
    public List<Order> order { get; set; }
}

public class Column
{
    public string data { get; set; }
    public string name { get; set; }
    public bool searchable { get; set; }
    public bool orderable { get; set; }
    public Search search { get; set; }
}

public class Search
{
    public string value { get; set; }
    public string regex { get; set; }
}

public class Order
{
    public int column { get; set; }
    public string dir { get; set; }
}
/// End- JSon class sent from Datatables

Next implement your action in a standard controller (note in this example we are not using a Web-API controller)

This method just grabs the data sent from the table and calls YourCustomSearchFunc() before returning a formatted json obj for Datatables to consume.

public JsonResult CustomServerSideSearchAction(DataTableAjaxPostModel model)
{
    // action inside a standard controller
    int filteredResultsCount;
    int totalResultsCount;
    var res = YourCustomSearchFunc(model, out filteredResultsCount, out totalResultsCount);

    var result = new List<YourCustomSearchClass>(res.Count);
    foreach (var s in res)
    {
        // simple remapping adding extra info to found dataset
        result.Add(new YourCustomSearchClass
        {
            EmployerId = User.ClaimsUserId(),
            Id = s.Id,
            Pin = s.Pin,
            Firstname = s.Firstname,
            Lastname = s.Lastname,
            RegistrationStatusId = DoSomethingToGetIt(s.Id),
            Address3 = s.Address3,
            Address4 = s.Address4
        });
    };

    return Json(new
    {
        // this is what datatables wants sending back
        draw = model.draw,
        recordsTotal = totalResultsCount,
        recordsFiltered = filteredResultsCount,
        data = result
    });
}

YourCustomSearchFunc() is very simple it just sets up the sort column and sort direction before calling the database search functionality. In this example we are only allowing sorting on a single column but you could easily implement multi column sorting.

public IList<YourCustomSearchClass> YourCustomSearchFunc(DataTableAjaxPostModel model, out int filteredResultsCount, out int totalResultsCount)
{
    var searchBy = (model.search != null) ? model.search.value : null;
    var take = model.length;
    var skip = model.start;

    string sortBy = "";
    bool sortDir = true;

    if (model.order != null)
    {
        // in this example we just default sort on the 1st column 
        sortBy = model.columns[model.order[0].column].data;
        sortDir = model.order[0].dir.ToLower() == "asc";
    }

    // search the dbase taking into consideration table sorting and paging
    var result = GetDataFromDbase(searchBy, take, skip, sortBy, sortDir, out filteredResultsCount, out totalResultsCount);
    if (result == null)
    {
        // empty collection...
        return new List<YourCustomSearchClass>();
    }
    return result;
}

This is the main meat of the functionality. In it we simply select from the dbase but instead of using a fixed where clause we use a dynamic expression built using the wonderful LinqKit to generate the predicate.

Additionally we use Take and Skip to allow us to page through the data. Notice we use the where clause twice. Once to select the data and pick a page, the second time to count how many items we could have returned.

public List<YourCustomSearchClass> GetDataFromDbase(string searchBy, int take, int skip, string sortBy, bool sortDir, out int filteredResultsCount, out int totalResultsCount)
{
    // the example datatable used is not supporting multi column ordering 
    // so we only need get the column order from the first column passed to us.         
    var whereClause = BuildDynamicWhereClause(Db, searchBy);

    if (String.IsNullOrEmpty(searchBy))
    {
        // if we have an empty search then just order the results by Id ascending
        sortBy = "Id";
        sortDir = true;
    }

    var result = Db.DatabaseTableEntity
                   .AsExpandable()
                   .Where(whereClause)
                   .Select(m => new YourCustomSearchClass
                   {
                       Id = m.Id,
                       Firstname = m.Firstname,
                       Lastname = m.Lastname,
                       Address1 = m.Address1,
                       Address2 = m.Address2,
                       Address3 = m.Address3,
                       Address4 = m.Address4,
                       Phone = m.Phone,                      
                       Postcode = m.Postcode,                      
                   })
                   .OrderBy(sortBy, sortDir) // have to give a default order when skipping .. so use the PK
                   .Skip(skip)
                   .Take(take)
                   .ToList();

    // now just get the count of items (without the skip and take) - eg how many could be returned with filtering
    filteredResultsCount = Db.DatabaseTableEntity.AsExpandable().Where(whereClause).Count();
    totalResultsCount = Db.DatabaseTableEntity.Count();

    return result;
}

Here is the predicate builder function that just plugs in a where clause dynamically. You will need to install (nugget) in linqkit for this.

In this example I am searching where the searchterm appears in either the firstname or lastname

private Expression<Func<DatabaseTableMappedClass, bool>> BuildDynamicWhereClause(DBEntities entities, string searchValue)
{
    // simple method to dynamically plugin a where clause 
    var predicate = PredicateBuilder.New<DatabaseTableMappedClass>(true); // true -where(true) return all
    if (String.IsNullOrWhiteSpace(searchValue) == false)
    {
        // as we only have 2 cols allow the user type in name 'firstname lastname' then use the list to search the first and last name of dbase
        var searchTerms = searchValue.Split(' ').ToList().ConvertAll(x => x.ToLower());

        predicate = predicate.Or(s => searchTerms.Any(srch => s.Firstname.ToLower().Contains(srch)));
        predicate = predicate.Or(s => searchTerms.Any(srch => s.Lastname.ToLower().Contains(srch)));
    }
    return predicate;
}

The only left to show is the datatable itself

var table = $('#SearchResultTable').DataTable({
    "proccessing": true,
    "serverSide": true,
    "ajax": {
        url: "@Url.Action("CustomServerSideSearchAction", "Home")",
        type: 'POST'
    },
    "language": {
        "search": "",
        "searchPlaceholder": "Search..."
    },
   "columns": [
        { "data": "Firstname" },
        { "data": "Lastname" }
    ]
});

Hope this helps

When Datatable Editor has an server error adding or updating, how to notify the client?

$
0
0

Let's say we are adding a record, and that event fails on the server side. Is there a form of data that can be returned which will show the error message? I'd like my program to be able to send a server side message back.


How to solve the problem that the child form and parent form are not aligned

$
0
0

The inner and outer tables have the same structure, and the inner layer has no header. After embedding, the sub-table is shifted to the right as a whole.

How to search for subtable data

$
0
0

There is a sub-table in the table object. When searching, the contents of the sub-table cannot be filtered.My code is as follows:

var type = $.fn.dataTable.util.escapeRegex(param.type),
typeIdx =3;
tableObj.column(typeIdx ).search(type !=='all' ? '^'+filterNeType+'$' : '' , true,false).draw();

In datatables,How can we cascade dropdown data while using multiple dropdowns for search

$
0
0

Datatables according to us has fantastic features. We have found lots of solutions from this forum. Thanks.
We were trying to build a search with dropdown values. All is well but for this case.
Simple Example Scenario to help understanding(not the real case) -
Datatables shows country city and say population
Say we have a dropdown search for country and city
When country dropdown has a value selected for country , only the cities of that country should be shown in the city dropdown.
How can this be achieved ? We are using the standard way ie code in the initComplete method for populating the dropdowns.

Calculate sum using sum api question

How to Update Changed Values in a Data Table.

$
0
0

Hi,
I need help to fix issue,
I have checkbox control with unique Id in my data table.
I want to check and uncheck that checkboxs form my java script function.
But this happen only my current page on rest page it's still remaining.
Help me to fix this problem.

This is a online Link which clear what i really need. - http://live.datatables.net/tuzifaxe/134/
(Check CheckBoxes Page 1 and Page 2, after press button which is given bottom grid, checkbox clear current page checks only.)

Calculate average of rounded columns

$
0
0

How can I calculate the average of columns that are shown like this :

98.50 %
99.39 %
78.30 %
84.98 %

Any ideas? I'll have to format the numbers, and then use the average function on it, but I have yet to find a method :(

Datatable in tabs not always responsive

$
0
0

I have implemented two tabs containing one datatable each respectively. The code for each tab is exactly the same, it is only the data that is different. For some mind-boggling reason, the tables behave in different ways and neither is reliably responsive. The first tab is responsive on alternating clicks (once yes, once no) whereas the second tab is not responsive on the first click, then is always responsive. This result arose from adding responsive.recalc() to a timeout function, before doing this the tabs were not behaving responsively at all.

The code which links the tab to the tab functionality is the following:

    $('#test_history').on('shown.bs.tab', function (e) {
        if (test_table == null) {
            GET_test_history();
        }
        else {
                test_table.responsive.recalc();
        }
    });

This is the code for the initialization of the first datatable:

function init_test_datatable() {
        $.fn.dataTable.moment('DD/MM/YYYY');
        var unorderable_columns = [];
        var datefrom_dropdown_name = "disphist_filter_date_from";
        var dateto_dropdown_name = "disphist_filter_date_end";
        var date_change_draw_counter = { counter: 0 }; 
        var unorderable_columns = [2, 3];

        test_table = $('#test_table').DataTable({
                "dom": '<"row dt-filter-row"<"col-lg-3 col-md-4 col-sm-5 search-filter-container" f><"col-lg-9 col-md-8 col-sm-7 date_range_filters_container">>Bprtip',
                "aaData": testlist,
                "bPaginate": true,
                "pageLength": 50,
                "aoColumns": [
                    {
                        "className": 'details-control none td-no-right-border',
                        "orderable": false,
                        "mData": "test_details",
                        "defaultContent": '',
                        "searchable": true
                    },//0
                    {
                        "mData": "test_date",
                        "searchable": true,
                        "defaultContent": '',
                        "orderable": true
                    },//1
                    {
                        "mData": "test_descr",
                        "searchable": true,
                        "orderable": true,
                        "defaultContent": '',
                        "className": 'all left-align-td nowrap-column',
                    },//2
                    {
                        "mData": "test_entitled",
                        "orderable": false,
                        "defaultContent": '',
                        "className": 'center-align-td'

                    },//3
                    {
                        "mData": "test_amount",
                        "orderable": false,
                        "defaultContent": '',
                        "className": 'center-align-td'
                    },//4
                ],
                "order": [[1, "desc"]],
                "pagingType": "numbers",
                "language": {
                    "sSearch": search_label,
                    "emptyTable": no_data_string,
                    "lengthMenu": datatables_lengthMenu,
                    "info": datatables_info,
                    "infoFiltered": datatables_infoFiltered,
                    "infoEmpty": datatables_infoEmpty,
                    "zeroRecords": datatables_zeroRecords
                },
                "columnDefs": [
                    { "orderable": false, "targets": unorderable_columns }
                ],
                "buttons": [
                    {
                        text: '<i class="fa fa-filter-slash"></i><span class="toHideMax520">' + " " + ClearFilters_Button + '</span>',
                        action: function (e, dt, node, config) {
                            date_change_draw_counter.counter = 2;
                            $('#test_table' + '_wrapper .date-range-filter').datepicker('clearDates');
                            test_table.search("").draw();
                            $("#test_table_filter input").removeClass("active_filter");
                            $(".date-range-filter").removeClass("active_filter");
                        }
                    },
                    {
                        text: '<i class="fa fa-history"></i><span class="toHideMax520">' + " " + "Load Older History" + '</span>',
                        action: function (e, dt, node, config) {
                            //clear filters
                            date_change_draw_counter.counter = 2;
                            $('#test_table' + '_wrapper .date-range-filter').datepicker('clearDates');
                            test_table.search("").draw();
                            $("#test_table_filter input").removeClass("active_filter");
                            $(".date-range-filter").removeClass("active_filter");
                        }
                    },

                ]
            });
        $('#test_table').show(); //css is set as display:none initially 

        setTimeout(function () { test_table.responsive.recalc(); }, 1000);
}

HTML of the table is the following:

<div class="tab-content" style="padding-top:1em">
    <table id="test_table" class="table table-striped table-bordered dt-responsive" cellspacing="0" style="width:100%">
        <thead>
            <tr>
                <th>Test Details</th>
                <th>Test Date</th>
                <th>Test Item</th>
                <th>Test Entitled</th>
                <th>Test Amount</th>
            </tr>
        </thead>

        <tbody id="test_body"></tbody>
    </table>
</div>

Any help at all would be really appreciated!


Datatables takes TOO much time

$
0
0

Hello Everybody.
I have to launch 8 tables on a same page and it takes about 45 sec to load them but :
- Most of them are only 1 or 2 rows long, only one is more than 20 rows.
- Each request launched in toad are less than one sec to give answers even for the biggest.

I already tried processing, serverSide and deferLoading but no signifiant difference.

Please could you tell me why my request are going from 798ms in toad to 5 sec in jquery ???
What am i doing wrong ?

here is my js code :
$( '#'+table ).dataTable(
{
"bProcessing": true,
destroy : true,
paging : false,
jQueryUI : false,
autoWidth : false,
// processing : true,
// serverSide : true,
// "deferLoading" : 10,
pageLength : 20,
lengthMenu: [ 20, 50, 100, "All" ],
responsive : true,
oLanguage :
{
"sZeroRecords" :"Aucun élément à afficher",
"sLengthMenu" :"Afficher MENU éléments",
"sProcessing" :"Traitement en cours...",
"sInfo" :"Affichage de l'élement START à END sur TOTAL éléments",
"sInfoEmpty" :"Affichage de l'élement 0 à 0 sur 0 éléments",
"sInfoFiltered" :"(filtré de MAX éléments au total)",
"sInfoPostFix" :"",
// "sSearch" :"Rechercher:",
"sUrl" :"",
"oPaginate" :
{
"sFirst" :"|<",
"sPrevious" :"<",
"sNext" :">",
"sLast" :">|"
}
},
ajax : "php/listing_accueil.php?Couleur="+table+"&date_saisie="+$("#DateSaisie").val()+"&Matin_Aprem="+$("input[class='MATIN_APREM']:checked").val(),
dom : '',
initComplete : function( settings, json )
{
$('.loader').fadeOut();
$('.table_de_donnees').fadeIn("Slow");
},
"drawCallback" : function(settings)
{
var iTotalRecords = settings.fnRecordsTotal();
console.log(iTotalRecords);
$('#Consultants'+table).html(iTotalRecords+' <small class="text-right">CLAUDON R.</small>');
}
} );

field names not escaped in php code when using serverside filtering

$
0
0

we have a table that uses serverside filtering.

the Editor PHP code is handling the serverside part of this table.

        $ed = Editor::Inst($db, 'mailbox_queue', 'index')
            ->fields(
                Field::inst('testbed'),
                Field::inst('link'),
                Field::inst('remarks'),
                Field::inst('date_add'),
                Field::inst('date_parsed')
            )
            ->$ed->process( $_POST )
            ->$ed->json();

Now this code first does a count on the table and generates below query

SELECT  COUNT(index) as 'cnt' FROM  `mailbox_queue`

inside the Count() function the field names are not escaped and mysql/mariadb errors on this.

The escaped query works

SELECT COUNT(`index`) as 'cnt' from mailbox_queue

I know index is a reserved keyword, but if escaped it should work, we are migrating a legacy application so we can not simply change the fieldname.

`table.ajax.reload()` won't work

$
0
0

I am having a input field on my front end where I accept a code which is used to fetch data from the backend and display it in datatable. I am making a ajax call to bring that data to the front. But when I change the value in the input field (and try to update data in datatable using table.ajax.reload()) , the ajax call by the datatable holds on to older code. So the table wont get updated. Please help.


"ajax" : { url : "/my/url", dataSrc:"",` data:{'form':$("#my_id").serialize() , 'csrfmiddlewaretoken':csrf_token}, contentType : "application/json", complete: function(data){ $(".overlay").hide(); }, success: function(){ console.log("ajax successful"); } },

Does anyone have an example of using the unique() function?

$
0
0

I would like to make a specific column only display an End Model once. Or is there a way to pull the data into the Datatable using Select Distinct in the query, maybe?

Fixed header with scrollX and scrollY

$
0
0

.withOption('scrollY', '250px')
.withOption('scrollX', true)
.withOption('scrollCollapse', true)
not working.please help me.

Viewing all 82216 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>