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

Problem with sum

$
0
0

Hello,

I have a problem with a sum column. The result isn't exactly. I have 321.84999999999997 but it's 321.85.
I tried differents js:

1st solution:

  $(document).ready(function () {

                 var table = $('#summary').DataTable({
 "footerCallback": function ( row, data, start, end, display ) {
            var api = this.api(), data;

            // Remove the formatting to get integer data for summation
            var intVal = function ( i ) {
                return typeof i === 'string' ?
                    i.replace(/[\$,]/g, '')*1 :
                    typeof i === 'number' ?
                        i : 0;
            };
// Total hours over this page
            thisPageTotal = api
                .column( 13, { page: 'current'} )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );

 // Update footer
            $( api.column( 13 ).footer() ).html(
                thisPageTotal + ' heure(s) sur cette page'
       {# ( sur '+ allPagesTotal +'  heure(s) totale(s))'#}
            );
        }   
});

2nd solution:

                $.fn.dataTable.Api.register('column().data().sum()', function () {
                                 return this.reduce(function (a, b) {
                                     var x = parseFloat(a) || 0;
                                     var y = parseFloat(b) || 0;
                                     return x + y;
                                 });
                             });

                 $(document).ready(function () {

                                     var table = $('#summary').DataTable({
                $('<button>Cliquez pour avoir la somme des coûts de M.O. de la sélection</button>')
                                        .prependTo('#summary')
                                        .on('click', function () {
                                            alert('Column sum is: ' + table.column(13).data().sum());
                                        });
                            });

3rd solution:

jQuery.fn.dataTable.Api.register('sum()', function ( ) {
                return this.flatten().reduce(function (a, b) {
                    if (typeof a === 'string') {
                        a = a.replace(/[^\d.-]/g, '') * 1;
                    }
                    if (typeof b === 'string') {
                        b = b.replace(/[^\d.-]/g, '') * 1;
                    }

                    return a + b;
                }, 0);
            });
$(document).ready(function () {

                                         var table = $('#summary').DataTable({
                    $('<button>Cliquez pour avoir la somme des coûts de M.O. de la sélection</button>')
                                            .prependTo('#summary')
                                            .on('click', function () {
                                                alert('Column sum is: ' + table.column(13).data().sum());
                                            });
                                });

An idea?


Export to excel button freezing browser with ~20,000 rows

$
0
0

I am running into an issue and am hoping for some guidance, even if it is that I am going about this type of thing the wrong way. In any event, I have a datatable that is dynamically generated with data from a remote API. The table(s) contain a decently large quantity of data (up to 20k rows and 10-20 columns, some with HTML text of varying length).

Smaller exports (<10k rows) download, but it takes roughly 4-5. When I try to export the full table, though, the browser becomes unresponsive and the download never happens.

Does anyone have any suggestions? Should I expect a download of this size to not time out the browser? If so, are there any other options using the DataTables library?

how do I add an index to a row when I create using the API ?

$
0
0

I'm using row.add() to dynamically add rowsfrom JSON structures arriving down a websocket. From then on I need to update rows whenever data for that row arrives down the websocket. I've done this previously using simple html tables and id's and am trying to use Datatables instead but i can't figure how to (a) add an id when I create the row, and then (b) access that row when I have new data for it.
I appreciate I'm new and might not have read the docs correctly - any help very much appreciated,
thx,
Gav

Using as an Attendee Register

$
0
0

Hi Guys,

Sorry, noob alert. Running through the Pusher Real-time Tables got me wondering about a application for my sons sports club. They meet for practice twice a week and each time someone has to produce a paper form to take some information of the attendee's. The data we collect is:-

{First Name} {Last Name} {Member} {Kit Hire} {Cost}

The 'Cost' depends on member status and 'Kit Hire'

Would it be possible to generate a table with current date inserted as an identifier, add new attendee (if necessary, like the example in the link above), then save the current table and be able to retrieve that data at a later time.

I hope that makes sense. It would basically be like save the paper forms but obviously online.

Thanks in advance.

PHP -> NodeJS

$
0
0

Hi,
I'm converting a project from PHP to NodeJS, in PHP I'm passing a variable to PHP how do I do this in node?

JS side:
        editor = new $.fn.dataTable.Editor( {
            ajax: {
                url: 'php/table.MuffinLift.php',
                type: 'POST',
                data: function ( d ) {
                    d.WorkOrder = JobNumber;
                }
            },

PHP side:
    ->debug( false )
    ->where( 'MuffinLift.JobNumber', $_POST['WorkOrder']) 
    ->process( $_POST )
    ->json();

DataTable jQuery plug-in dynamic table creation and data

$
0
0
        var isPostBack = false;
        var dataSet = null;

        function dataParse()
        {
            document.getElementById("resultSet").innerHTML = "";

            sqlStatements = 
            [
                `SELECT * FROM ? WHERE chapterIdSequence = 22`,
                `SELECT * FROM ? WHERE bookId = 43 AND chapterId = 1`
            ];

            for
            (
                var sqlStatementId = 0, 
                    sqlStatementIdCount = sqlStatements.length;
                sqlStatementId < sqlStatementIdCount;
                ++sqlStatementId
            )
            {
                var alasResult = alasql
                (
                    sqlStatements[sqlStatementId], [dataSet]
                );


                var resultTable = document.createElement("table");
                resultTable.id = "resultTable" + sqlStatementId;
                let myTable = $('#' + resultTable.id).DataTable
                ( 
                    {
                        "data": alasResult,
                        "columns": [
                            { "data": "verseIdSequence" },
                            { "data": "scriptureReference" },
                            { "data": "KingJamesVersion" }
                        ],
                        destroy: true
                    }
                );
                //document.getElementById("resultSet").appendChild(myTable);
                $("#resultSet").append(myTable);
                //scriptLiteral9432.renderDataTable(alasResult, "resultSet")
            }
        }

        function querySubmit()
        {
            if (dataSet) { dataParse(); return; }
            var request = {};
            //request["scriptureReference"] = scriptureReference;
            var requestJson = JSON.stringify(request);

            $.ajax
            ({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: 
                    "/WordEngineering//AlaSQL.js/AlaSQL.js_-_OnlyRefuseSubstainTheLine.asmx/Query",
                data: requestJson,
                dataType: "json",
                success: function(data) 
                {
                    dataSet = JSON.parse(data.d);
                    dataParse();
                },
                error: function(xhr)
                { 
                    $("#resultSet").html
                    (
                        'Status: ' + xhr.status + " | " + 
                        'StatusText: ' + xhr.statusText + " | " +
                        'ResponseText: ' + xhr.responseText
                    );
                } 
            });
        }

        function pageLoad()
        {
            if (isPostBack === false)
            {
                $.getScript
                ( 
                    "/WordEngineering/WordUnion/9432.js", 
                    function( data, textStatus, jqxhr ) 
                {
                    var scriptureReference = 
                        scriptLiteral9432.getParameterByName
                        (
                            "scriptureReference"
                        );
                    if (scriptureReference)
                    {
                        document.getElementById
                        (
                            "scriptureReference"
                        ).value = scriptureReference;
                    }   
                    scriptLiteral9432.renderBibleVersionSelect();
                    var bibleVersion = 
                        scriptLiteral9432.getParameterByName
                        (
                            "bibleVersion"
                        );
                    if (bibleVersion)
                    {
                        document.getElementById
                        (
                            "bibleVersion"
                        ).value = bibleVersion;
                    }   
                    querySubmit();
                    isPostBack = true;  
                });
            }
            else
            {
                querySubmit();
            }
        }

        window.addEventListener("load", pageLoad, false);

        document.getElementById
        (
            "submitQuery"
        ).addEventListener
        (
            "click",
            querySubmit,
            false
        );

Bubble editing - how do you set up a multiple select dropdown menu?

$
0
0

Can you point me to an FAQ or example code for how to set up a multiple select menu in the bubble editor? The assumption is that I would use the control key to select multiple items (or perhaps shift+ ). The plan - I'm setting up a function which will make it possible to select all, all but, none or individual items in a list.

This may involve adding two functions - one a simple dropdown for 'all', 'all but', 'none'. The second would be the multiselect list of choices - the subject of this question.

Pattern to launch form from other form?

$
0
0

I have a backend database with a clients table and an events table. From the events table view, there will be an create/edit event form with select field to select an existing client. But if a new client is detected somehow ('new' button next to client select? simply type new client name in select window?), I'd like a client form to be launched over top of the events form to collect the client information and perform the ajax create client.

Is there any pattern I can look at that does something like this?


Autofill drop error after edit cell

$
0
0

Dear Alan!
The datatables autofill drop error when i begin select edited cell. (mouse down in small blue rectangle)
If I step another cell with right arrow key, and step back left arrow key, (the edited cell is active, but not editing) the select is good and autofill is runing.
Uncaught TypeError: Cannot read property 'offsetParent' of undefined
at AutoFill._getPosition (dataTables.autoFill.js:606)
at AutoFill._drawSelection (dataTables.autoFill.js:397)
at AutoFill._mousedown (dataTables.autoFill.js:662)
at HTMLDivElement.<anonymous> (dataTables.autoFill.js:170)
at HTMLDivElement.dispatch (jquery-latest.js:1549)
at HTMLDivElement.r.handle (jquery-latest.js:1489)

the error is _getPosition: function, currOffsetParent = $( currNode[0].offsetParent ); line, because the currNode will emty object after parrent is nothing.
You use back tested cycle:
do{..
currOffsetParent = $( currNode[0].offsetParent )
...
currNode = currOffsetParent;
...
} while ( currOffsetParent.get(0) !== targetParent.get(0))

This run when currOffsetParent.get(0) !== targetParent.get(0) because You set currNode the parentNode, and the parrentNode nothing, the next cycle run will drop this error.
I use editor, scroller, button, selector, keytable, fixed column and autofill, and I use server side, and not use pager.
And the second problem:
After the autofill is runing, (no error, and selected cell is replaced) the selected cell box is active and drop same error, wheni not change to another column.

If i change another column the select is will good, the previously selected box is nothig, and no drop error.

Any idea? (I use too many extension, and they will problem?)
I not can make sample program, because i use server side select own php , and i use mysql 8 json field to store data.

Add mysql Details on external file

$
0
0

I am using this code

<?php

/*
 * DataTables example server-side processing script.
 *
 * Please note that this script is intentionally extremely simply to show how
 * server-side processing can be implemented, and probably shouldn't be used as
 * the basis for a large complex system. It is suitable for simple use cases as
 * for learning.
 *
 * See http://datatables.net/usage/server-side for full details on the server-
 * side processing requirements of DataTables.
 *
 * @license MIT - http://datatables.net/license_mit
 */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Easy set variables
 */

// DB table to use
$table = 'new';

// Table's primary key
$primaryKey = 'id';

// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
    array( 'db' => 'name', 'dt' => 0 ),
    array( 'db' => 'country',  'dt' => 1 ),
    
    
);

require( 'mysql.php' );


); 

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */

require( 'ssp.class.php' );

echo json_encode(
    SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);

and my mysql.php is this

$sql_details = array(
    'user' => 'root',
    'pass' => '123',
    'db'   => 'doo',
    'host' => 'localhost'


I don't know what i am missing

Thanks in advance for answer

DataTables-Editor-Server Method not found: System.String.Split

$
0
0

Hello

I require .NET Framework 4.5.1 for OWIN packages I am using.
Should DataTables-Editor-Server work with .NET Framework 4.5.1?

The Demo for .NET Framework 4.5 work perfectly.

I installed DataTables-Editor-Server in my projects via NuGet Package manager
When calling editor.Process(formData) I get the following error:

$exception {"Method not found: 'System.String[] System.String.Split(Char, System.StringSplitOptions)'."} System.MissingMethodException

Is there a way around this without changing the Framework to 4.5?

Server side processing of 200 000 rows but Allowed memory size of exhausted and Invalid JSON respons

$
0
0

Hello,

I tried to use Datatable for displaying a long query of 250 000 rows with 22 columns. For that, I use server side processing, but with SSP::complex and joins table. I don't have any error in the sql query (when I test it in phpmyadmin this display well all the rows), but in my json return I have the error "Allowed memory size of 536870912 bytes exhausted ". And in my datatable "Invalid JSON response" (due to the allowed memory error ?).

I thought server side processing ask automtically the database with limit query to have only a smaller number of rows than the entire count of result.

Did I miss something or done something wrong ?

Upgrading from 1.10.15 to 1.10.18 breaks (multiple column) smart filtering?

$
0
0

Hey all,

when I wanted to upgrade from the above mentioned versions, it broke my "Search all columns"-function. I've both tried the search-API and the (apparently legacy) fnFilter with the same problem. When reverting back to the old version it works again. The code I am using is:

$(tableID).DataTable().search(searchValue).draw();
--- or ---
$(tableID).DataTable().search(searchValue, false, true).draw(); // Regex = false, Smart = true
--- or ---
$(tableID).dataTable().fnFilter(searchValue);

What I wanted to achieve is the same as this example when the user wants to search for "Airi Satou Accountant". In my local case, "Airi Satou " is found, but when searching for "Airi Satou A" there are no entries found anymore.

At this rate I am forced to downgrade to 1.10.15 again.

With best regards.

Centering button

Delay issue on event

$
0
0

hi

i have an datatable.

On every row i have a button to delete. When i click on the row i would like to display the record.

So i have two operation to do for the click.

when document is ready, i do

                var urlI18n = '/i18n/' + '[(${#authentication.getPrincipal().getLang()})]' + '.json';
                    var url = "/samplings";
                    
                    var samplingsTable = $('#samplingsTable').DataTable({
                        language: {
                            url :  urlI18n
                        },
                        bLengthChange: false, //hide 'show entries dropdown
                        processing: true,
                        serverSide: true,
                        pagingType: 'simple_numbers',
                        dom: 'Bfrtip',
                        buttons: [
                            {
                                text: '[(#{sampling.new})]', //should come from thymeleaf
                                action: function (e, dt, node, config) {
                                    $("#samplingsFragment").load("/template/new/samplings");
                                },
                                 init: function(api, node, config) {
                                    $(node).removeClass('btn-secondary');
                                    $(node).addClass('btn-primary');
                                }
                            }
                        ],
                        initComplete: function() {
                            var $searchInput = $('div.dataTables_filter input');

                            $searchInput.unbind();

                            $searchInput.bind('keyup', function(e) {
                                if(this.value.length > 2) {
                                    samplingsTable.search( this.value ).draw();
                                }
                            });
   
                            
                        },
                        ajax: {
                            type: 'get',
                            url: url,
                            data: function (d) {
                                var current = $('#samplingsTable').DataTable();
                                d.page = (current != undefined) ? current.page.info().page : 0;
                                d.size = (current != undefined) ? current.page.info().length : 5;
                                d.sort = d.columns[d.order[0].column].data + ',' + d.order[0].dir;
                                d.search=d.search.value;
                            }
                        },
                        columns: [
                            {data: 'compositeId'}, 
                            {data: 'buildDate'},
                            {data: 'productTypesName'},
                            {data: 'productsName'},
                            {data: 'machineName'},
                            {data: null, orderable: false, defaultContent: ' <i class="fas fa-trash-alt delete"></i>'}
                        ],
                        createdRow: function( row, data, dataIndex ) {
                           
                            $( row ).find('td:eq(0)').attr('data-id', data.id);
                            $( row ).find('td:eq(1)').attr('data-year', data.year);
                        }
                    });
                    
                    $("#samplingsTable tbody tr td:not('.delete')").on('click', function (e) {
                    
                        e.preventDefault();
                    
                        console.log("not delete operation");
                        var data = samplingsTable.row(this).data();

                        var id = data.id;
                        var year = data.year;

                        var url = '/template/edit/samplings/year/' + year + '/id/'+id;
                        $("#samplingsFragment").load(url);

                    });
                    
                    $("#samplingsTable").on('click', '.delete', function(e) {
                        e.preventDefault();
                        
                        var samplingsId=$(this).parents('tr').find('td:eq(0)').attr('data-id');
                        var samplingsYear=$(this).parents('tr').find('td:eq(1)').attr('data-year');
                        var id=samplingsYear+""+samplingsId;
                        var row =  $(this).parents('tr');
 
                        var url = "/samplings";
                     
                        bootbox.confirm({
                            title: /*[[#{delete}]]*/,
                            message: /*[[#{delete.entity}]]*/,
                            buttons: {
                                cancel: {
                                    label: '<i class="fa fa-times"></i> ' + [[#{no}]]
                                },
                                confirm: {
                                    label: '<i class="fa fa-check"></i> ' +  [[#{yes}]]
                                }
                            },
                            callback: function (result) {

                                if(result){
                                    deleteEntity(url, id); 
                                }
                            }
                        });
  
                    });

Actually they seem to have a delay issue.

Click on delete is working but not the other one... =>tbody tr td:not('.delete')

in debug when i do a copy paste in cosole it working...


ColReorderWithResize don't ellipse text

$
0
0

I have ColReorderWithResize and it is awesome, but I need a update, because it work fine only if I enlarge the column, but when I restrict the column and the column has the text long, the size of the column don't restrict than the length of the text.
sorry for my bad english...

I would to do same thing like this: http://www.visailing.com/include/tablesorter/docs/example-widget-resizable.html

that is, when I restrict the column and the text is more big then the text ellipse with dots.
can you help me?

how to get a list of value

$
0
0

Hi All:

I have a datable that have 100 rows with the 5th column with the balances.
10 records per page, so there is 10 pages.

I need to get a list of the array of the balance for the 100 rows and check each balance if it is over 100 or less than .10.
Is there an api to get a list of the balances so I can loop through it and see each balance to see if it's over 100 or less than 10 cents.

Any help or hint would be greatly appreciated it.

Official version of Bulma theme for Datatables

$
0
0

Hey,

do you have any plans on creating Datatables theme based on Bulma CSS framework?
Foundation is supported officialy and is less popular than Bulma (27k vs 30k Github stars) so I think that Bulma does deserve some attention.

Also there are several unofficial packages but one with over 300 downloads per week.

Appreciate your answer and consideration.

Have a nice day!

Searching with render function...

$
0
0

Hi,

I am using Datatables with ajax calling a server side script to get the result-set from a MySQL database. For some of the columns, I need to modify the text that needs to be displayed e.g.

data: null,
render: function ( data, type, row, meta ) {
      return row.manufacturer + " (" + row.model + ")";
    }

The column correctly displays the text. But when I try to search for either the manufacture or model, no results come up. I am searching from the UI using the Datatables builtin input box. Any idea how can I include the manufacturer and/or model in the search?

Many Thanks!

Angular 6 - Table draw() is not redrawing table correctly with updated data

$
0
0

So I build my tables into Angular 6 and they each get created in ngOnInit(). There is also an editing feature on some fields that will send a PUT request to my server. This works and updates the current value of the element in the table and the value of the object in the server.

Whenever I call my PUT request I also have
this.table.draw();
on successful request. This command runs, but when I try to sort my new data via the column arrows it is still sorting as if there was no change. When I refresh the page I can now sort correctly. But I don't want our users to have to refresh to sort or search their data correctly.

Here's my code:

ngOnInit() {
    const subscription = this.dataService.getClientData().subscribe(val => {
        this.clients = val;
        console.log(this.clients);

        this.chRef.detectChanges();

        this.table = $('table').DataTable({
          'destroy': true,
          'paging': true,
          'info': true,
          'autoWidth': true,
          'responsive': true,
          scrollY: '600',
          // scrollCollapse: true, // fixedHeader will be disabled, but will fix some scrolling issues
          scrollX: true,
        });
        this.showSpinner = false;
    });
  }

//Called on table element EDIT
updateContract(value, client) {
    // PUT req
    if (client.contractType === value) {
      return;
    }
    client.contractType = value;

    this.options = {
      host: this.buildUrl(client)
    };
    this.sendPutRequest(this.options.host, client, this.options);
  }

sendPutRequest(updateUrl, client, options) {
    this.http.put(updateUrl, client, options).subscribe(
      val => {
        console.log('PUT call successful value returned in body', val);
      },
      response => {
        console.log('PUT call in error', response);
      },
      () => {
        console.log('The PUT observable is now completed.');
        this.table.draw();      // Command is RUNNING but table is not UPDATING
        console.log('Table redrawn');
      }
    );
  }
Viewing all 82311 articles
Browse latest View live


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