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

Writing DT Unit Tests

$
0
0

Hi everyone, this is kind of a basic question, but I thought I would post it here in the event that it helps someone else. I'm curious to learn what frameworks the community uses for writing Unit Tests on DataTables, as well as any hints/tips/tricks that you use. We're looking at our code and planning to start writing tests for it and would love to know the various approaches taken.

Thanks!


Unable to filter null values using (select inputs) filter drop-down for Datatable

$
0
0

Dear All,

I have data table where it's working perfectly fine. But I need to filter the data table column even for null values.
And I also need to display the value "Empty" or "Null" in (Select) filter drop-down to filter the Data Table column having null values.
If you see below I have blank value in drop-down which indicates the column is having null values.
Fiddle

trouble with regex OR searching

$
0
0

Hello, I am trying to enable regex searching to allow for filtering for two values on one column, i.e. "val1|val2". This feature seems well documented and I have looked at and tried to follow the given examples.

I followed this example to add search bars to each column, and slightly modified it to move them to the header instead of the footer (and this was done successfully, works just fine):
https://datatables.net/examples/api/multi_filter.html

To search using '|' (OR), I have read the following:
https://datatables.net/reference/api/search()
https://datatables.net/examples/api/regex.html

It would seem all I need to do is edit the .search() line...

.search( this.value, true, false )

but when I try this I get "No matching records found" upon using "val1|val2"
I have also tried adding the following to the datatable initilization:

"search": { "regex": true },

I can filter a single value of any column just fine, I just get nothing when trying two values with an '|' (OR)
here is all of my code:

$(document).ready(function(){

        // Setup - add a text input to each footer cell
        $('#datatable tfoot th').each( function () {
            var title = $(this).text();
            $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
        } );
        $('#datatable tfoot tr').appendTo('#datatable thead');

        // DataTable + Initialization
        var datatable = $('#datatable').DataTable({
            "bServerSide":true,
            "ordering":true,
            "paging":true,
            dom: 'Bltip',
            scrollY: "40vh",
            scrollX: "20vh",
            "sAjaxSource":"{% url 'tabledata' %}",
            "search": { "regex": true },
            buttons: [
                'copyHtml5',
                'excelHtml5',
                'csvHtml5',
            ]
        });

        // Apply the search
        datatable.columns().every( function () {
            var filteredCol = this;

            $( 'input', this.header() ).on( 'keydown', function (ev) {
                if ( ev.keyCode == 13 ) {
                    filteredCol
                        .search( this.value, true, false )
                        .draw();
                }
            } );
        } );

    });

Running the debugger... I see this under table state...
Global Filter -

{
    "bCaseInsensitive": true,
    "sSearch": "",
    "bRegex": true,
    "bSmart": true,
    "_hungarianMap": {
        "caseInsensitive": "bCaseInsensitive",
        "search": "sSearch",
        "regex": "bRegex",
        "smart": "bSmart"
    },
    "regex": true
}

Column Filter (for every column) -

[{
    "bCaseInsensitive": true,
    "sSearch": "",
    "bRegex": false,
    "bSmart": true
}, {

editor set value as boolean for a checkbox sends an array instead of a boolean

$
0
0

I have a backend server that is expecting a response in the form of a boolean. I've been following this example exactly as what is posted in this demo example:

https://editor.datatables.net/examples/api/checkbox.html

I have the following field on the editor:

      {
        label: "Active",
        name: "active",
        type: "checkbox",
        options: [
          { label: '', value: true }
        ]
      }

Executing the following code:

    _editor
      .edit($(this).closest('tr'), false)
      .set('active', true)
      .submit();

Send the following value to the server:

"[\r\n  1\r\n]"

Setting the field to false:

    _editor
      .edit($(this).closest('tr'), false)
      .set('active', false)
      .submit();

Send the following value to the server:

"[]"

These results aren't what I'd expect when setting a checkbox value with a boolean type. Why can't I just receive a simple "true" or "false" value? As this complicates my code on the backend.

Then I investigated what was going on:

var _editor = new $.fn.dataTable.Editor({
    ajax: {
          url: '/api/Test',
          data: function (d) {
              var id;
              switch (d.action) {
                    case "create":
                         id = 0;
                         break;
                    case "edit":
                    case "remove":
                         id = d.data[Object.keys(d.data)[0]].ID;
                         break;
              }
              console.log(d.data[id].active);   //weird results
              return JSON.stringify(d);
      },
     ....
    }
});

In the console log, I found out that if the value is true, then d.data[id].active is an array with one index, with the value true. And if the value is false, then d.data[id].active is undefined.

Is there a reason why this logic exists like that? It took me forever to find out what was going on and why my server kept blowing up. To remedy this, in the ajax code I did this:

  var retVal = false;
  if (d.data[id].active.length > 0) {
      retVal = d.data[id].active[0]
  } 
  d.data[id].active = retVal;
  return JSON.stringify(d);

rowReorder: the dragged row jumps back to its old position

$
0
0

Hi,

After dragging a row, should the table not be displayed in its new state?

When I drag a row and drop it, it jumps back to its old position. The data of the 'row-rorder' event is correct though, so if I save the new order in the database and reload the table with table.ajax.reload(), the changes become visible. But that is not visually beautiful.

I have only the option "rowReorder: { selector: 'tr' }" when I initialize the table. Can't find anything else in the documentation...

Regards,
Edwin

Is there an issue with ckeditor5 balloon? Seems not to work with plugin.

$
0
0

Hello all,
it seems that the ckeditor 5 plugin does not work if type is ckeditorBalloon.
ckeditorClassic runs fine with the same example. But if I change to ckeditorBalloon, the editor field will not replaced with the ballooneditor. I used the cdn from ckeditor for ballon and also for classic (of course not at the same time).
Is there a way to get the balloon editor work with datatables editor?
Frank

Excel export does not export the data in the table just the name and table headings

$
0
0

I am trying to export a table of data extracted by Java, passed back to Ajax using JSON, and populating the table with Ajax in HTML. Using a table populated with data in the HTML works fine.

Java:

    if (packSummaryList == null || packSummaryList.isEmpty()) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No one joined.");
    } else {
        String json = new Gson().toJson(packSummaryList);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }

Ajax:

      .done(function(responseJson1a){
            dataType: "json";
    var tablebody = "";
    try{
          for (i=0; i < responseJson1a.length; i++) {
              tablebody += "<tr><td>"+responseJson1a[i].section+"</td><td>"+responseJson1a[i].metricTotal+"</td></tr>";
          }
          $("#mytablebody").empty();
          $("#mytablebody").append(tablebody);
    }
    catch(e){
    console.log(e);
    }
})

HTML:

    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <table class="table table-hover table-bordered" id="joinedTable">
            <thead>
                 <tr>
                    <th>Section</th>
                    <th>Joined</th>
                 </tr>
            </thead>
            <tbody id="mytablebody"></tbody>
        </table>
        <div style="text-align: center;">
            <span id="ajaxGetUserServletResponse1" style="color: red;"></span>
        </div>
     </div>

The excel export exportOptions trim property not working

$
0
0
"buttons": [
                {
                    extend: 'excelHtml5',
                    title: $(".companyName").text(),
                    filename: $('#reportTitle').text().trim(),
                    "createEmptyCells" : true,
                    sheetName: excelSheetName,
                    messageTop: $(".stdReportTitle").text(),    
                        exportOptions: {
                                        trim : false;
                                    }
                    customize: function( xlsx ) {   
                                       // my code
                                    }
                            }
];

The trim property not working. I want to excel exported cell content with empty spaces before text;
Ex:
Cell sting is " text"

Please help me. The cell contents are trimmed by default when i export


Extract data from other tables to be able to export an excel

$
0
0

How can I get data from other HTML tables and my table so I can export it to an excel with the buttons function

Daterangepicker plug-in adjustment to have predefined date ranges

$
0
0

Hi,

I'm trying to adjust this Daterangepicker plug-in, however no luck so far.

So far my naive approach has been to merge the plug-in code above with working code from other part of my app, where in addition to regular daterangepicker boxes there predefined date ranges shown:

var lng = $('body').data('locale');
moment.locale(lng);

//daterangepicker
(function( $, DataTable ) {
    'use strict';


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

    var _fieldTypes = DataTable.Editor ?
            DataTable.Editor.fieldTypes :
            DataTable.ext.editorFields;

    _fieldTypes.daterangepicker = {
        create: function ( conf ) {

            conf._input = $('<input/>')
                    .attr( $.extend( {
                        id: conf.id,
                        type: 'text'
                    }, conf.attr || {} ) )
                    .daterangepicker( conf.opts || {} );

            return conf._input[0];
        },

        get: function ( conf ) {
            $(conf._input).data('daterangepicker').elementChanged(); //Update dates of the picker from input
            return conf._input.val();
        },

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

    };

    var start = moment();
    var end = moment().add(365, 'days');

    function cb(start, end) {
        $('input[id="DTE_Field_valid_from_to"] span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
    }

    $('input[id="DTE_Field_valid_from_to"]').daterangepicker({
        startDate: start,
        endDate: end,
        ranges: {
           [I18n.t('daterangepicker.today')]: [moment(), moment()],
           [I18n.t('daterangepicker.yesterday')]: [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
           [I18n.t('daterangepicker.last_7_days')]: [moment().subtract(6, 'days'), moment()],
           [I18n.t('daterangepicker.last_30_days')]: [moment().subtract(29, 'days'), moment()],
           [I18n.t('daterangepicker.this_month')]: [moment().startOf('month'), moment().endOf('month')],
           [I18n.t('daterangepicker.last_30_days')]: [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        locale:{
          "format": "DD.MM.YYYY",
          "separator": " - ",
          "customRangeLabel": I18n.t('daterangepicker.custom_range'),
          "applyLabel": I18n.t('confirm'),
          "cancelLabel": I18n.t('cancel')
        }
    }, cb);

    cb(start, end);

})(jQuery, jQuery.fn.dataTable);

At the moment I see my calendar is localized, which probably comes from moment.locale(lng); but I do not see predefined date ranges.

Is there any way to do the adjustment, please? Thank you!

DOM changes in Server-side processing Datatable

$
0
0

Hi,
I have created a server-side datatable, with a specific DOM

<'row'<'col-6'i><'col-6'f>>" +
"<'row'<'col-12'tr>>" +
"<'row'<'col-8'l><'col-4'p>>

Now, with all the DOM changes, like filter/length-change/pagination, the api to get that particular data runs. But recently, I included, 'Z' to the DOM for column-resize, and even on column resize, the api runs, which is uneccessary. Is there a way of stopping this API execution on column resizing?

Thanks in advance.

Server side using nodejs error on search with client side columns

$
0
0

I'm using nodeJS server side processing. My tables has two columns that are both set to 'searchable: false' and 'orderable: false' but when searching or ordering nodeJS errors with the following: 'UnhandledPromiseRegectionWarning: Error: Unknown field: empty (index 0)'

I can see the request being sent has 'columns[0][searchable]: false' and 'columns[0][orderable]: false' in the data so it appears client-side its ok but server side seems to be ignoring that.

Has anyone experienced this with nodejs? and any ideas on a solution?

Botón x en el campo de búsqueda

$
0
0

Hola, no tengo el botón x para borrar el campo de búsqueda, lo he visto en varios ejemplos pero no se lo que necesito.

moment.js missing when running generator

$
0
0

Hello, I just wanted to mention that when I run the generator and select moment, then the page won't show properly because its not included

I guess you can see it when you run it. Or maybe it was a one time glitch but I thought I report it.

Thanks

datatable version 1.10.6 does not support destroy and column adjust.

$
0
0

Hi Allan,

Can you please tell me why datatable version 1.10.6 does not support destroy and column adjust?
====[code]====
$('id').Datatable().destroy();
$('id').Datatable().columns.adjust().draw();
====[code]====
Any help would be appreciated.
Thanks in advance.

Pankaj Sharma


How do i download pdf as same as it is displaying the application?

$
0
0

Hi all,
I am a newbie to this forum and am working on data tables export. I want to make PDF and print task for my project. For my task, I need to show the same count as in the application to the print paper and as well as pdf.


I have shared a screenshot. In the first screenshot, am showing only 10 persons so I want to show only that 10 persons in the print and PDF. How can I make it? Can anyone help me on this?

Thanks in advance.

Images doesn't display correctly

$
0
0

I have a table with a column in which I show images loaded by Django.

Each time I reload the page, the images change, although the reference to them in the HTML is correct.

That is, if I look at the URL of the image, it is correct, but the image that is displayed does not correspond to the url.

This happend with every browser.

Thanks so much

Limit on Multiedit?

$
0
0

Hi,
I have a data table with about 1000 records. Using MultiEdit function, I can edit 100 records at the same time, but with 200 records the server responds with Error 403 (Forbidden). I don't know the reason, maybe too much POST data? I have tried the option submit: 'changed' , but it seems this does not work on MultiEdit: it submits the whole row anyway.
Is there any idea how I would be able to multiedit all 1000 records?
Many thanks and regards,
marwi

Search hide instead of remove

$
0
0

Hello,

I am using a table in my form, however when i post that form only the displayed options are posted, not the rest, is it possible for Datatables to hide the elements, instead of removing them from the DOM?

Thanks in advance!

DataTable is showing object object in columns

$
0
0

I am trying to populate DataTable with my Data but DataTable is showing **object **in columns and not printing the actual values!

JSON:

https://pastebin.com/NUEaMVn3

JS:

// Init the DatTable using the Cx Admin DataTable plugin
    cx.common.data.cxAdminDataTables.EbEvaluationSymptom = $CxRecordsTable.cxAdminDataTable({
        ajaxUrl: '<?php echo $this->CxHelper->Route('eb-admin-get-evaluation-symptoms')?>',
        columns: [
            cx.common.admin.tableEditColumn('id'),
            { data: 'title' },
            { data: 'remedy' },
            { data: 'additional-remedy' },
            { data: 'date_created' }

        ],

    });
Viewing all 82273 articles
Browse latest View live


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