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

Examples needed - Button in rows with hover menu

$
0
0

Any Datatable examples of tables with a button(s) with a hover menu for options? I'm trying to implement this in a project of mine but cannot get this to work. when I take this code an paste it into a new html file with only the button (no table content) it works fine.

  //$.fn.dataTable.ext.errMode = 'throw';

   $(document).ready(function() {
     $('#tabemcurso').DataTable(
     {
         processing:true,
         dom:'lftBip',
         buttons: [
         'copy', 'excel', 'pdf'
     ],

         //select:true,

       pageLength:10,
       scrollY: "300",
       scrollX: "100%",
       "ajax": {
         "method":"POST",
         "url":"list.php"
       },
       "columns":[

         {"data":"Null",
             "defaultContent": '<div class="dropdown"><button onclick="btnFunction()" class="dropbtn">...</button><div id="mydrop" class="dropdown-content"><a href="#">Some Option</a></div></div>'},
         {"data":"Proj_ID"},
         {"data":"Proj_Nome"},
         {"data":"Cliente"},
                 ],

          AutoWidth:true,
          "fnCreatedRow": function( nRow, aData, iDataIndex ) {
           $(nRow).children("td").css("overflow", "hidden");
           $(nRow).children("td").css("white-space", "nowrap");
           $(nRow).children("td").css("text-overflow", "ellipsis");
           },
     });
   });

How do i make a datatables editor view show the lookup labels instead of values

$
0
0

for example

    var editor = new $.fn.dataTable.Editor( {
        ajax: 'js/DataTablesEditor/php/table.trailer.php',
        table: '#trailer',
        fields: [

            {
                "label": "ID",
                "name": "id_trailer",
                "type": "readonly"

            },

            {
                "label": "Trailer #",
                "name": "number"
            },

            {
                "label": "Type",
                "name": "type",
                "type": "select",
                "options": [
                    { label: 'van', value: 'van' },
                    { label: 'reefer', value: 'reefer' },
                    { label: 'flatbed', value: 'flatbed' },
                    { label: 'container', value: 'container' },
                    { label: 'rail', value: 'rail' }
                    // etc
                    ]
            },

            {
                "label": "Length",
                "name": "size"
            },

            {
                "label": "Carrier",
                "name": "id_carrier"
            },

            {
                "label": "Status",
                "name": "id_trailer_status"
            },

        ]
    } );

    var table = $('#trailer').DataTable( {
        dom: 'Bfrtip',
        ajax: 'js/DataTablesEditor/php/table.trailer.php',
        columnDefs: [
                { targets: [ 0 ], visible:false },
                { targets: [ 5, 8 ], render:function ( data, type, row, meta ) {
                    return ((data=='1')?'<img src="img/greencheck.png" width="15" alt="1" />':'<img src="img/redx.png" width="15" alt="0" />');
                    } },
                { targets: [ 2,4,6,7 ], render:function ( data, type, row, meta ) {
                    console.log(data,type,row,meta);
                    if (false == true) alldd.ddval({name: 'carrier',type:'val',ref:$(this),arg:data});
                    return (data);
                    } },
            ],
        columns: [

            { "data": "id_trailer" },
            { "data": "number" },
            { "data": "type" },
            { "data": "size" },
            { "data": "id_carrier" },
            { "data": "id_trailer_status" },
            { "data": "trailer_owned" },
            { "data": "id_condition" },
            { "data": "in_yard_status" },

        ],
        select: true,
        lengthChange: false,
        buttons: [
            { extend: 'create', editor: editor },
            { extend: 'edit',   editor: editor },
            { extend: 'remove', editor: editor }
        ]
    } );

How do i show the label for type (column 3) and the label for id_carrier (5) . Also how do i get the values for the editor for a select box (they are in separate tables)?

Unifying the select field width

$
0
0

I have multiple select boxes in my editor but they are all different width depending on the widest option. Is there a way to unify the width of all the select fields in the editor menu?

Combine select and input

$
0
0

Hi, is it posible to combine two different field types in DataTables Editor?
I mean, if I want to allow users to pick one option from a select, or allow them to type new content, if this content is not in the list.
With the code:

label: "Usuario:",
name: "Usuario",
type: "select",
ipOpts: getUsuarios()

the users can only select one item of the list, but they cannot type a new user.

Intervals Editor for Datatables editor jquery.

$
0
0

i have a field which represents a delay time in seconds. i want to edit it as hours minutes seconds with something like datetimepicker - any ideas. The formatting of static display is easy,

/*
 * Editor client script for DB table detention_rules
 * Created by http://editor.datatables.net/generator
 */

(function($){
    function sec2intvl( data, type, full, meta ) {
        var secs = parseInt(data);
        var hours = Math.floor(secs / 3600);
        var r = secs - (hours * 3600);
        var rmin = Math.floor(r / 60);
        var rsec = r - (rmin * 60);

        var a = ("0" + hours);
        var ret = a.substr(a.length - 2, 2) +':' ;
        a = ("0" + rmin);
        ret += a.substr(a.length - 2, 2) +':';
        a = ("0" + rsec);
        ret += a.substr(a.length - 2, 2);

        return (ret);
        }

$(document).ready(function() {
    var editor = new $.fn.dataTable.Editor( {
        ajax: 'js/DataTablesEditor/php/table.detention_rules.php',
        table: '#detention_rules',
        fields: [
            {
                "label": "ID",
                "name": "detention_rules.detention_rule_id",
                "type": "readonly"
            },
            { "label": "Name", "name": "detention_rules.rule_name" },
            { "label": "Grace Time", "name": "detention_rules.grace_sec" },
        ]
    } );


    var table = $('#detention_rules').DataTable( {
        dom: 'Bfrtip',
        ajax: 'js/DataTablesEditor/php/table.detention_rules.php',
        columnDefs: [ { targets: [ 0 ], visible:false }, ],
        columns: [
            { "data": "detention_rules.detention_rule_id" },
            { "data": "detention_rules.rule_name" },
            { "data": "detention_rules.grace_sec", "render" : sec2intvl},
        ],
        select: true,
        lengthChange: false,
        buttons: [
            { extend: 'create', editor: editor },
            { extend: 'remove', editor: editor }
        ]
    } );

    $('#detention_rules').on( 'click', 'tbody td', function (e) {
        editor.inline( this, {
            submit: 'changed',
            submitOnBlur: 'true'
        } );
    } );

} );

}(jQuery));

php is:

<?php

/*
 * Editor server script for DB table DetentionTables
 * Created by http://editor.datatables.net/generator
 */

// DataTables PHP library and database connection
include( "lib/DataTables.php" );

// Alias Editor classes so they are easy to use
use
    DataTables\Editor,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Mjoin,
    DataTables\Editor\Upload,
    DataTables\Editor\Validate;

// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'detention_rules', 'detention_rule_id' )
    ->fields(Field::inst( 'detention_rules.detention_rule_id' )
            ,Field::inst( 'detention_rules.rule_name' )
            ,Field::inst( 'detention_rules.grace_sec' )
            )
    ->process( $_POST )
    ->json();


Buttons Print - Microsoft Edge

$
0
0

Hello,

I seem to be having an issue with the Buttons extension, specifically when it comes to the print button. I am running Windows 10 and I found in Microsoft Edge when I click print, instead of showing the printer dialog along with the page to print, it only comes up and says blank page.

I figured it may be something in my code but all of the examples are doing the same thing.

Has anyone else run into this issue?

Scott

Can i use SQL in Server side scripting

$
0
0

Hi Allan,
Can i use SQL where i can use where and group by clause .
Please give me example.

Regards.
Sunil

How do I use the `ajax` function option properly?

$
0
0

I'm struggling to understand the proper way to use the function option for ajax. I load data from a REST API that returns batches of results and continuation tokens (the data set can be very large). I cache these results so I don't have to hit the server every time I redraw or change pages. I also support a "load more" feature when I want more data from the server.

The ajax function provides a callback that the documentation says I'm supposed to call when I have all my data. But getting all the data can take a while, so I want to render the data chunks as they come in. I also want to preserve the current page as data comes in.

Here's a simplified example of what I'm working with.

import * as bluebird from "bluebird";

interface Pair {
    name: string;
    value: any;
}

interface ContinuationResult<T> {
    next: any;
    result: T;
}

let table: DataTables.DataTable;
let cache: Pair[] = [];
let recordsPerSecond = 3;
let totalRecords = 45;

async function render(settings: DataTables.Settings, json: any): Promise<void> {
    if (cache.length > 0) {
        // Cache hasn't changed. No need to re-render.
        return;
    }

    let chunk: ContinuationResult<Pair[]> = null;
    do {
        let next = chunk && chunk.next;
        if (next) {
            chunk = await getChunk(next);
        } else {
            chunk = await getChunk();
        }

        // Call the DataTables callback to render the data.
        // It's possible this is the wrong way to do this. In which case, the API should be used instead.
        chunk.result.forEach((row) => {
            cache.push(row);
            table.row.add(row);
        });
        table.draw(false);
    } while (chunk.next);
}

async function getData(data: Object, callback: Function, settings: DataTables.SettingsLegacy): Promise<void> {
    if (cache.length > 0) {
        return callback({ aaData: cache });
    }

    let chunk: ContinuationResult<Pair[]> = null;
    do {
        let next = chunk && chunk.next;
        if (next) {
            chunk = await getChunk(next);
        } else {
            chunk = await getChunk();
        }

        // Call the DataTables callback to render the data.
        // It's possible this is the wrong way to do this.
        cache = cache.concat(chunk.result);
        callback({ aaData: chunk });
    } while (chunk.next);
}

async function getChunk(next: any = 0): Promise<ContinuationResult<Pair[]>> {
    await bluebird.delay(1000);

    let chunk: Pair[] = [];
    for (let i = next; i < next + recordsPerSecond; i++) {
        chunk.push({ name: i, value: Math.random() });
    }

    return { result: chunk, next: next <= totalRecords ? next + recordsPerSecond : null };
}

$(document).ready(() => {
    table = $("#datatable").DataTable({
        ajax: getData,
        // initComplete: render,
        pageLength: 10,
        paging: true,
        pagingType: "full_numbers",
        processing: true,
        serverSide: false,
        stateSave: false,
        columns: [
            {
                name: "Name",
                data: "name"
            },
            {
                name: "Value",
                data: "value"
            }
        ]
    });
});

No Parameterless Constructor for DtRequest

$
0
0

Hello, I've been using DataTables with C# MVC sites for a bit and have been trying out Editor recently. In the past, I've made my own DTParams object to catch the parameters sent to the controller for server side processing, but in trying out Editor, I see that there's a DtRequest type included, which seems to serve the same purpose.

The one hangup I'm having is that I'm getting a 'No parameterless constructor' error when trying to use the DtRequest type for an object as a parameter for a JsonResult method that handles the data processing on the server side.

Is this the intended usage of DtRequests type, or should I continue using the params object I have in the past?

add function to own pagination through callback

$
0
0

Hello,

Im not sure if this is prossible, but I need add function to my pagination through callback

I think that fnDrawCallback is what will be needed, and my request:

$.extend($.fn.dataTableExt.oPagination, {
'fnClickHandler': function(e) {
//add function through fnDrawCallback
},
'fnInit': {},
'fnUpdate': {}
}

$('#table').DataTable({
'fnDrawCallback': function(oSettings) {
//how??
}
}

I need add this to fnDrawCallback, Set hash after click f.e. index.html?page=12

Url.updateSearchParam('page', oSettings.oInstance.fnPagingInfo().iPage + 1);

It working, but for all pagination and I need set just for some of them

'fnClickHandler': function(e) {
var fnCallbackDraw = e.data.fnCallbackDraw;
var oSettings = e.data.oSettings;
var sPage = e.data.sPage;
oSettings.oApi._fnPageChange(oSettings, sPage);
fnCallbackDraw(oSettings);
Url.updateSearchParam('page', oSettings.oInstance.fnPagingInfo().iPage + 1);
return true;
}

How to add second footer to print in Tfoot?

$
0
0

Guys, I can't print the second footer in <tfoot> tag?
How can I resolve this issue?

Copy to clipboard not working with Multiple headers

$
0
0

Hi, I am using copy to clipboard function on a table with 2 headers. The 1st header spans on multiple columns as one can expect. Now most of the export functions such as pdf/excel or copy to clipboard only copies the 2nd header but not the first header. Any thoughts on how to fix?

draw Datatable after Date range

$
0
0

Hi,
i am having problem datatable draw after date range. by default i am loading current moth data into table. if user select a date range. i send a query request to PHP script to get the specified date range data. i am getting data from server in following format.
when i use table.rows.add().draw() it is not adding the newly data into table.

[["2017-02-02 00:19:15","000201068","240xxxxxxx","4","D2C-EXTEN","Taxi"],["2017-02-02 00:24:51","000201068","247xxxxxxx","13","D2C-EXTEN","Taxi"],["2017-02-02 00:37:59","000201058","206xxxxxxx","31","D2C-EXTEN","Taxi"]]

here is my ajax call

$("#end_date").on('change', function (){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
table.clear();
$.ajax({
"type": "POST",
"url": "recordsdate.php",
"data": {start_date: start_date,
end_date: end_date,
},
success: function (data){
console.log(data);
table.rows.add(data).draw();
}
});
});

JQuery Datatable issue with json object: Maximum call stack size exceeded

$
0
0

Hi All,

Need help in resolving Jquery datatable issue.

I am using Jquery datatable (version 1.10.13) to generate HTML table using ajax call.
But every time I am trying to display the table I am getting below error in Chrome (56.0.2924.76 (64-bit))

Uncaught RangeError: Maximum call stack size exceeded
at RegExp.test (<anonymous>)
at Number.<anonymous> (jquery-1.12.4.js:10034)
at Function.each (jquery-1.12.4.js:370)
at buildParams (jquery-1.12.4.js:10033)
at buildParams (jquery-1.12.4.js:10055)
at buildParams (jquery-1.12.4.js:10055)
at buildParams (jquery-1.12.4.js:10055)
at buildParams (jquery-1.12.4.js:10055)
at buildParams (jquery-1.12.4.js:10055)
at buildParams (jquery-1.12.4.js:10055)

And no records are displayed though 8 rows have returned as resultset.

Screen Work flow.
1. User selects search Criteria and clicks search to get the results.
2. The resultset is wrapped in Json object and returned to JS callback method.
3. Callback method is used to render the JS datatable (version 1.10.13).

Inside callback method:

$('#divID).css('display','block');
$("#tableID").DataTable().destroy();
.$('#tableID).dataTable({..
..
........code for datatable config
...})
$('#tableID').DataTable().draw();

Any help would be much appreciated!!!

Export datatables to pre-formatted excel file.

$
0
0

Good Day Everyone, i just want to ask, is there a feature in 'datatables excel export' that it can be exported to a pre-formatted excel file? Just like PHPExcel if you're familiar with it.

Because i have seen the export to excel option but i can't see any that can make this happen(export to pre-formatted excel file)

Any advice will be gold to me thanks!


running totals and accessing other rows from meta

$
0
0

Hi,

I'm trying to make a running total column in a table.

A solution I came up with accesses the value of a cell in the previous row using:

meta.settings.aoData[meta.row-1].anCells[3].innerText

but this seems a little hacky, is there a better way?

code here:
http://codepen.io/jasonblewis/pen/egVPNP?editors=0010

any advice would be appreciated.

Move to record added or edited

$
0
0

Hi,

I have a datatable set up as follows:

    $("#tblList").DataTable({
        "ajax": {
            "url": "/projects/ajaxTableData"
        },
        "fixedHeader": true,
        "scrollY": "200px"  ,
        "scroller": true ,
        "columns": [{"data": "cAction",             "width": "20px",    "orderable": false},
                    {"data": "iNum",                "width": "50px",    "orderable": true},
                    {"data": "cStatus",             "width": "70px",    "orderable": true},
                    {"data": "cName",               "width": "100px",   "orderable": true},
                    {"data": "dRequested",          "width": "70px",    "orderable": true},
                    {"data": "dRequired",           "width": "70px",    "orderable": true},
                    {"data": "cProjectLeader",      "width": "100px",   "orderable": true},
                    {"data": "cComment",            "width": "450px",   "orderable": false},
                    {"data": "nPercentComplete",    "width": "50px",    "orderable": true}
                   ]
    });

Note that I am using scrollY with scroller and I am using an ajax datasource.

When I add a row, I am adding it to the back end table and then doing an ajax.reload(). When I edit a row, I update the back end and do the same. WHat I would like to do is then move the table so that the edited row is the first row shown/the added row is at the last row visible (if I have to put the added row as the first visible row, that's OK too).

Any ideas on how I might accomplish this?

Remove row, then change page, row is still present

$
0
0

I am loading my datatable from json using javascript on the client. My data is loaded fine. I make some changes to a row, post back the data changes to my server, await a response, and if the response is successful, I remove the row and redraw the table. After removing the row, the row is gone from the datatable, but it reappears after I change pages or pageLength via that show entries per page drowdown control.

What can I do to completely remove the row from the database source so paging will not make it reappear?

Below is my code, shortened for this example.

$('#myTable').DataTable({
    "paging": true,
    "ordering": true,
    "info": true,
    "pageLength": 15,
    "fixedHeader": true,
    "data": ds,
    "columnDefs": [
        // column defs here...
    ],
});

$('.btn-save').on('click', function(e) {
    var row = $(e.currentTarget).closest("tr");
    var data = $('#myTable').dataTable().fnGetData(row);

    var json = {}; // I actually create real json, as not shown

    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(json),
        url: Routes.ROUTE_TO_MY_CONTROLLER,
        success: function (json) {
            if (json && json.success){
                // I have tried them all, they do remove from
                // the table, but once I change pages, they are
                // still there.
                row.remove().draw(true);
                //row.remove().draw(false);
                //row.remove().draw();
            }
        },
        error: function (textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
});

Format exported pdf file as its text is overwriting on each other

$
0
0

Hi, I am using datatables to PDF export option but when I export it with too much it overwrites the data. The data comes above each other and look very akward and distorted.

Here is an image of the example. Please look at it.

[

](

"

")

I want to fix that issue ( data above on each other ). Can we get it fixed by styling the pdf file?

Inline editor issue with canReturnOnSubmit for disabled fields

$
0
0

When the inline editor has formOptions.inline configured to submit the form on return, the return key doesn't submit fields with fields.type set to "readonly", or any field that has been disabled using the disable.

Uncaught TypeError: Cannot read property 'canReturnSubmit' of null

My first impression is that Editor tries to read property canReturnSubmit of the current field, which is null because disabled fields can't have focus.

I suggest that the inline Editor should always call close when the return key is pressed on a disabled field, regardless of the form options.

Viewing all 82461 articles
Browse latest View live


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