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

custom editorFields is it possible to pass data from than one column via additional methods

$
0
0

Using a custom editor field is it possible to pass data from another table column into the set method

I am attempting to do pass the value of another column as an additional option to a custom editor. Hopefully the markup below will clarify my issue.

{
    label: "Status:",
    name: "Status",         // this a text description of the status as sent by the server
    type: "MyCustomEditor", // my custom editor that will format the status with an icon and text (no input field)

    ?????????
    customOption: {
        // how do I pass in the status code value from another column into this custom editor
        name:"StatusCode"   // StatusCode comes from server (1,2,3,4) etc only use is to choose icons and colours for the status description
    }
},

More complete sample

 _fieldTypes.RowStatus = {

    var statusValueFromTable; // 0,1,2,3,4 etc

    ?????????
    customOption:function(conf, val)
    {
        statusValueFromTable = val;
    }

    create: function (conf) {
        conf._input = $("<span></span>");
        return conf._input;
    },

    set: function (conf, val) {

        var iconInfoMap = [
            { colour: "grey", icon: "icon-pen" },
            { colour: "green", icon: "icon-check-mark" },
            { colour: "red", icon: "icon-cross" }
        ];

        ?????????
        iconInfo = iconInfoMap[statusValueFromTable];

        var html = '<span class="rowcolordatatable ' + iconInfo.colour + '"><i class="' + iconInfo.icon + '"></i><span> ' + val + '</span></span>';
        conf._input.html(html);
    },
};

editor = new $.fn.dataTable.Editor({
    "idSrc": "Id",
    "table": "#aTable",
    "fields":
    [
        {
            label: "Status:",
            name: "Status",
            type: "RowStatus",

            ?????????
            customOption: {
                // how do I pass in the status code value from another column into
                // this custom editor
                name:"StatusCode"   // want to pass 1,2,3,4 etc
            }
        },
        {
            // i can see the status code on the form easily but this is not what i want
            label: "StatusCode:",
            name: "StatusCode",
            type: "readonly",
        },
        {
            label: "City:",
            name: "Address3",
            type: "readonly"
        },
        {
            label: "Country:",
            name: "Address4",
            type: "readonly"
        }
    ]
});

 var table = $('#aTable').DataTable({

    "columns": [
      { "data": "Firstname" },
      { "data": "Lastname" },
      {
          "data": "StatusCode", render: function (data, type, row) {
              if (data == 1) {
                  return '<span class="gray"><i class="icon-pen"></i> <span>' + row.Status + '</span></span>';
              }
              if (data == 2) {
                  return '<span class="green"><i class="icon-check-mark"></i> <span>' + row.Status + '</span></span>';
              }
              if (data == 3) {
                  return '<span class="red"><i class="icon-cross"></i> <span>' + row.Status + '</span></span>';
              }
              // simplified ..
              return data;
          }
      },
    ]
});

$('#aTable tbody').on('click', 'button', function () {
    editor.edit($(this).closest('tr'), {
        ?????????
        // do i need to pass the statuscode value into the editor here??
        title: 'View Record',
    });
});

Progress bar is not rotating on editor while the request is being sent to server

$
0
0

Hi Allan,

The Progress bar is not rotating on the editor while the request is being sent to server (The progress bar is idle and not rotating). Also the progress bar is also not being displayed while uploading the image from editor. I am using editor v1.5.5 and "Bootstrap" styling instead of default. Could you please help me this? I would really appreciate your help.

Custom Filtering

$
0
0

Im using yadcf 1.10 and im trying to do the following:

i have a multi_select filter above some Columns and i want that only those rows are shown, which DONT contain the selected values.

Example:

| col1 |

| apple |
| beer |
| plant |
| tree |
| meat |
| fish |
| tree/beer |
| meat/apple |

==> i select apple AND beer:

| col1 |

| plant |
| tree |
| meat |
| fish |
| tree/beer |
| meat/apple |

==> cleared search and now selecting tree AND beer AND meat AND fish:

| col1 |

| apple |
| plant |
| meat/apple |

How can i do this server-side?

num-html does not work

How can I set the table instance or ID to use with stateSave?

$
0
0

I'm giving a little background here, but please bear with me as the question is still related to DataTables - I just wanted to explain the issue I'm facing:

Background:

I'm using DataTables in conjunction with a Javascript library called "Turbolinks" which basically turns your application into a Single Page Application (SPA) without all the overhead of using a true client-side framework. It is extremely useful for Ruby on Rails application performance.

There's a couple of headaches it introduces though - one is compatibility with DataTables. I've got it working pretty well by basically destroying any DataTable on a Turbolinks navigation, and then re-initializing it on turbolinks page load again. This method works well and seems to be the all-around accepted answer as to the best practice to get DataTables to work with Turbolinks.

Question:

On of the last features / finishing touches I'm trying to add to some of my applications is state saving. The issue I'm facing is that every time a table is destroyed/re-initialized on a page navigation, the...I'm actually not quite sure what to call it, but it looks like from inspecting the settings object on the stateSaveCallback - it looks like its the "sInstance" and/or the "sTableId": "DataTables_Table_0".

Then the localStorage key gets set as: DataTables_DataTables_Table_0_/current_path: "{data: data}", where current_path is whatever path/page you're on.

Then when it get re-initialized upon returning to the page, it gets set as DataTables_Table_1, and so on and so forth - so the state never gets correctly loaded.

Is there a way to override that ID so that it doesn't increase the last '0', '1', etc at the end of it? That way when the table is re-initialized, it will pull the saved state from just DataTables_Table/current_path?

Also open to other strategies of course.

how to use data-table in spa application

$
0
0

i create spa application with combined Knockout + CrossroadsJS + RequireJS.

pluck() on property derived from leftJoin

$
0
0

does anybody know why

        var Lat = table.rows( indexes ).data().pluck( 'Lat' );

works, but

        var Lat = table.rows( indexes ).data().pluck( 'fi_branch.lat' );

does not?
The result is undefinded.

Could it be that pluck() has a problem with joined tables?

The corresponding line from the php files would be:

        Field::inst( 'Lat' ),

and

        Field::inst( 'fi_branch.lat' ),

How can I detect a click on a field in the Editor?

$
0
0

I would like to perform some function when a field in the Editor popup is clicked.

How can I do this?

Regards,
Jim


Editor - split a database column data into two editor fields

$
0
0

I have a database column, "start", defined as type DATETIME.

In the editor I would like to split "start" into two editor fields, date and time, so I can use separate "pickers".

Likewise, once created/edited I would like to combine the date and time editor fields back into the database column "start".

I would like the date in "MM/DD/YYYY" format and time in "hh:mm a" format.

Being a bit new to Datatables and Editor, I'm not sure where to start..

Any examples would be welcome.

Regards,
Jim

Exceeding width problem, even with wrapper div.

$
0
0

Hi.

I'm starting to use DataTables, and I'm finding it wonderful. I know this has probably been asked here previously, but I believe my case may be different. I am using DataTables with the following configuration (JavaScript):

var tabeladt = $('#tab-teste-dt').DataTable(
{
    // "paging" : true,
    "pagingType": "simple_numbers",
    // "lengthChange": false,
        // "ordering" : true,
        // "searching" : false,
        // "info" : true,
    "serverSide" : true,
        "processing": true,
        "ajax" :
        {
            "url" : "lista-ajax",
        "type" : "POST",
        "dataType" : "json",
        "contentType" : "application/json; charset=utf-8",
        "async" : true,
        "cache" : false,
        "processData" : false,
        "data": function ( d )
        {
            return JSON.stringify( d );
        }
        },

        "columns" : [
                     {} ,
                     {} ,
                     {} ,
                     // Coluna 4...
                     { "render" : function(data , type , row , meta)
                         {
                            if(data.substr(0, 1) == "H")
                            {
                                return '<img src="/app/imagens/ico-h.png" />';
                            }
                            else if(data.substr(0,1) == "M")
                            {
                                return '<img src="/app/imagens/ico-m.png" />';
                            }
                            else
                            {
                                return data;
                            }
                         } } ,
                     {} ],

        "dom" : 'rt<"nav-dt"pl>',

        "language" : {
            "decimal":        ",",
            "emptyTable":     "Sem dados disponíveis no momento.",
            "info":           "Showing _START_ to _END_ of _TOTAL_ entries",
            "infoEmpty":      "Showing 0 to 0 of 0 entries",
            "infoFiltered":   "(filtered from _MAX_ total entries)",
            "infoPostFix":    "",
            "thousands":      ".",
            "lengthMenu":     "ITENS POR PÁGINA: _MENU_",
            "loadingRecords": "Carregando...",
            "processing":     "Processando...",
            "search":         "PESQUSIAR:",
            "zeroRecords":    "Nenhum registro foi encontrado.",
            "paginate": {
                "first":      "INÍCIO",
                "last":       "FIM",
                "next":       "SEGUINTE",
                "previous":   "ANTERIOR"
            },
            "aria": {
                "sortAscending":  ": activate to sort column ascending",
                "sortDescending": ": activate to sort column descending"
            }
        },

        // Extensão select!
        "select" :
        {
            'style': 'single'
        }
});

Here is my HTML markup:

<div class="conte-tabela" th:fragment="tabela-teste (titulo)">

    <!-- HEADER -->
    <div id="cabecalho">

        <!-- TITLE -->
        <span id="titulo" th:text="${titulo}">Título de tabela</span>

        <!-- OPTIONS BUTTONS -->
        <span id="opcoes">
            <button id="bot-pesquisa"></button><button id="bot-colunas"></button>
        </span>

        <!-- COLUMNS MENU -->
        <ul id="menu-colunas" class="popup-menu">
            <li th:each="col : ${#numbers.sequence(0 , colunas.length - 1)}">
                <label>
                    <input type="checkbox" th:value="${col}" th:text="${colunas[col]}" checked="checked">
                </label>
            </li>
        </ul>

        <!-- SEARCH MENU -->
        <div id="menu-pesquisa" class="popup-menu">
            <input type="text" placeholder="pesquisar por..."/>
        </div>

    </div>

    <!-- TABLE -->
    <table id="tab-teste-dt" class="stripe cell-border">
        <thead>
            <tr>
                <th th:each="coluna : ${colunas}"
                    th:text="${coluna}">
                    nome de coluna.
                </th>
            </tr>
        </thead>
    </table>

</div>

Note: There are some special elements from Thymeleaf (I'm a Java developer).

My CSS file:

.conte-tabela
{
    width: 80%;
    margin-left: auto;
    margin-right: auto;
}

.conte-tabela #cabecalho
{
    background: #474241;
    border-left: 1px solid #312e2d;
    border-right: 1px solid #312e2d;
    border-top: 1px solid #312e2d;

    width: 100%;
    display: table;

    padding: 14px 38px;
    box-sizing: border-box;
    position: relative;

    -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
    -khtml-user-select: none; /* Konqueror HTML */
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* Internet Explorer/Edge */
    user-select: none; /* Non-prefixed version, currently supported by Chrome and Opera */
}

.conte-tabela #cabecalho #titulo
{
    text-transform: uppercase;
    font-size: 10pt;
    font-weight: bold;
    color: white;

    display: table-cell;
    vertical-align: middle;
}

.conte-tabela #cabecalho #opcoes
{
    float: right;
    display: inline-block;
}

.conte-tabela #cabecalho #opcoes button
{
    background-color: #474241;
    border: 1px solid #312e2d;
    box-sizing: border-box;
    color: white; width : 40px;
    height: 40px;
    margin-left: 10px;
    width: 40px;

    background-repeat: no-repeat;
    background-position: center center;
}

.conte-tabela #cabecalho #opcoes #bot-pesquisa
{
    background-image: url("/app/imagens/ico-pesquisa.png");
}

.conte-tabela #cabecalho #opcoes #bot-colunas
{
    background-image: url("/app/imagens/ico-conf.png");
}

.conte-tabela #cabecalho #opcoes button:ACTIVE
{
    background-color: #312e2d;
}

.conte-tabela #cabecalho #menu-colunas
{
    margin: 0;
    padding: 20px;
    position: absolute;

    top: 100%;
    right: 38px;

    border: 1px solid #312e2d;
    background: #474241;

    z-index: 100;
    list-style: none;

    opacity: 0.9;
    display: none;
}

.conte-tabela #cabecalho #menu-colunas li
{
    color: white;
    padding-top: 10px;
    padding-bottom: 10px;
}

.conte-tabela #cabecalho #menu-colunas input[type="checkbox"]
{
    margin-right: 10px;
}

.conte-tabela #cabecalho #menu-pesquisa
{
    margin: 0;
    padding: 20px;
    position: absolute;

    top: 100%;
    right: 38px;

    border: 1px solid #312e2d;
    background: #474241;

    display: none;
    z-index: 100;
    opacity: 0.9;
}

Now, take a look at the attached image, please. See how the table exceeds the imposed width limits. If I uncheck the CSS stylization of "element", it get the right size. How can I fix this?

I am also using a separate CSS file to stylize the table in my way. In the case, I generated a theme for styling, and I'm using it as a style for my table. I copied the code and pasted it into a new file (CSS). This gave me full control over stylization, and created a locale for it. I'm saying this, because I do not know if what I did was correct. Since the DataTables styling file is kinda fat/big, I omitted it here. If it is necessary, I will put it here.

Thanks in advance.

Multiple KeyTable instances across multiple tables

$
0
0

I have two <table> elements on a single page. Each table element is associated to its own private DataTable instance (instead of a single DataTable instance that wraps multiple table elements). I would like to use KeyTable for keyboard navigation and Editor for inline editing in both tables.

The problem that I'm having is that all KeyTable instances listen for keydown events on the document element. In other words: when I press a key, all tables on my page respond to that key. This tends to break the code in unexpected ways because KeyTable event handlers are executed in a state that would not be possible if there was only a single table.

Example:
Focus a cell in one table and press enter to activate inline editing. All other tables on the page will also respond to the keypress, but the code will crash because there is no lastFocus.cell for Editor to start inline editing.

I don't know how to get around this since keypresses are handled globally instead of per table.

Increment/Decrement tool using Bootstrap and Fontawesome

$
0
0

I was looking for an increment/decrement tool that I could use within Datatables. I couldn't find anything that I liked so I put together this plug-in for the editor. This would also work for anyone that wants to use the Bootstrap input groups on their text fields.

You will need to have both Bootstrap and Font Awesome included in your project for this to work.

I've attached a screenshot of how it looks.

Here is the javascript

 //plugin increment and decrement numbers in the field.
    (function ($, DataTable) {

        if (!DataTable.ext.editorFields) {
            DataTable.ext.editorFields = {};
        }

        var Editor = DataTable.Editor;
        var _fieldTypes = DataTable.ext.editorFields;

        _fieldTypes.incrementor = {
            create: function (conf) {
                var that = this;
                conf._enabled = true;
                conf._input = $(
                    '<div >' +
                    '<div class="input-group">' +
                    '<span class="input-group-btn">' +
                    '<button type="button" class="btn btn-danger alter decrement"><i class="fa fa-minus fa-fw"></i></button>' +
                    '</span>' +
                    '<input id="' + Editor.safeId(conf.id) + '" type="text" class="incrementor" style="text-align:center;">' +
                    '<span class="input-group-btn">' +
                    '<button type="button" class="btn btn-success alter increment"><i class="fa fa-plus fa-fw"></i></button>' +
                    '</span>' +
                    '</div>' +
                    '</div>'
                    );

                return conf._input;
            },

            get: function (conf) {
                return conf._input.val();
            },

            set: function (conf, val) {
                var number = parseInt(val);

                $("input.incrementor", conf._input).val(number);

                $('.alter', conf._input).click(function () {
                    if ($(this).hasClass('increment')) {
                        number = parseInt(number) + 1;
                        $("input.incrementor", conf._input).val(number);
                    }
                    else if (number >= 1) {
                        number = parseInt(number) - 1;
                        $("input.incrementor", conf._input).val(number);
                    }
                });
            },
        };
    })(jQuery, jQuery.fn.dataTable);

Within the Editor field's

    $(document).ready(function () {
        Editor = new $.fn.dataTable.Editor({
            ajax: "/folder/mylink?str=@json",
            fields: [
                {
                    type: "incrementor",
                    label: "Field Title:",
                    name: "incrementingField",
                    default: '2',
                },
            ]
        });


        $('#changeLicenses').on('click', function () {
            Editor
                .buttons({
                    label: "Update",
                    className: 'btn btn-primary',
                    fn: function () { this.submit(); }
                })
                .title("Custom Title")
                .edit(ID);
        });
    });

Here is the CSS

.input-group { max-width: 281px; }

AJAX div .load calls and DataTables

$
0
0

At the moment I'm having a div reloaded by AJAX to have the navbar fixed without refreshing.
For instance;

      function callPage( pageRefInput ){
              $.ajax({
                url: pageRefInput,
                type: "GET",
                dataType: "html",
                success: function( response ) {
                  console.log('the page was loaded', response);
                  $('.content').html(response);
                },
          }),

This is all fine, loading PHP files where an page is in it, including a DataTables table with content from AJAX php/JSON.
Everything is loading, except the DataTables, where I do kind of understand that this has to be reloaded/reinitialising,
but can't get this to work. Or I get JSON errors, or just doesn't activate the plugin.

The DataTables JS file is as well in the PHP file.

After looking in Inspector, I figured out he doesn't want to load the DataTables content PHP file, even after;
$('#datatables').DataTable().ajax.reload();

Anyone have the same experiences, or ideas to figure this out?

Many thanks.

How to show info on records Dynamically

$
0
0

I'm using Datatables to show a table with 10K records. I'm showing 2K records at a time. When the table is loaded I have records from 0 - 2000, then if the button "next2K" is clicked, it reinitialize a new table with records from 2000 - 4000 and so on. I'm using the "info" attribute at datatables like this :

"info": "Showing START to END of TOTAL entries",
My problem is that when I have the records from 2000 - 4000, the "info" is like this :

Showing 1 to 10 of 2000 entries

But I want to show : Showing 2001 to 2010 of 4000 entries. Is there a way doing it using START , END , TOTAL ?

Use rowCallBack with moment.js

$
0
0

Hello,

Sorry if that's not clear, I'm not a native speaker.

I'm trying to display background-color on a row with rowCallBack and moment.js

If the date in a cell is before the actual date the row get colored.

Is that possible?

Here is what I tried:

$(document).ready(function() {
  var date = moment().format('DD-MM-YYYY')

  $('#dataTable').dataTable({
    retrieve: true,
    "rowCallBack": function(nRow, data, index){
      if (moment(data[5]).isBefore(date)) {
        $('td:eq(5)', row).css('background-color', 'red')
      }
    }
  })
});

Datatables - Responsive Row Trigger

$
0
0

https://datatables.net/reference/event/responsive-display

I'm having a issue where the ajax reload function is causing the datatables responsive plugin to close the open row details.
table.ajax.reload( null, false );

I'm aware of a workaround for select2 fields by listening for the ajax request (below) and I am confident I'll have to use this approach with this issue.
table.on('xhr.select2Fix', function(){

My question is can I trigger the responsive plugin to open a row ID manually (for my problem here I can simply record the rowID on this event)
table.on( 'responsive-display', function ( e, datatable, row, showHide, update ) {

or do I only have the option of using the button beside the row to toggle the expansion/retraction of the responsive display?

Join to 3 Tables

$
0
0

How to join 3 tables use Editör Class?

language.emptytable

$
0
0

table.fnSettings().oLanguage.sEmptyTable = "Now empty";

What is the equivalent for this in 1.10.11

Line Breaks not happening in the cells when using Export to Excel Button in Datatables

$
0
0

Hi,

I'm using render columns option in the columns to show the data with Line breaks in one of the columns in the grid.
But when i use the Export to Excel button functionality, all data is being populated in one line on the cell in the excel sheet even thought orthogonal in export options is default as display.

This is the code in datatable initialisation

buttons: [
{
extend: 'excel', text: 'Export to Excel', filename: 'Data export', exportOptions: {

                          orthogonal: {
                              display: ':null'
                          }
                      }
                  }],

"columns": [
{
"data": null,
"defaultContent": "<button id >Add</button>",
},
{ "data": "company", "autoWidth": true },
{
"data": "notes", "autoWidth": true,

                           "render": function (data, type, row) {
                               return data.split(", ").join("<br>");
                               console.log(data);
                           }

I have attached the images related to the grid and excel.
I'm not sure what i'm missing here. Any help would be appreciated.

Thanks,
Vishy

Button action

$
0
0

The names of several action functions for my buttons are stored in stables and available as a strings.
For example: we have button(5), the name of the action function for which is in a string which contains 'clickAdd()';
I wish to set the button action, at run time, using the function name 'provided as a string'.

First try:
var actionFuctionName = 'clickAdd()';
oTable.button(5).action( function ( e, dt, button, config) { actionFunctionName;});
The above does not work;

Second try:
oTable.button(idx).action( function ( e, dt, button, config) { eval(actionFunctionName);});
I have also tried the above, which does not work either.

However, in the console, the second try above does work, and the button behaves as required.

I have a sneaky suspicion the variable actionFunctionName is out of scope ... but, I'm not sure!

Appologies, as I am still relatively new to JS!

Thanks for hints and/or pointers to the appropriate datatables/JS documentation to do this!

Best regards from Montreal!

Viewing all 81390 articles
Browse latest View live


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