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

Leave the editor window open after creating a row and do not reset the form

$
0
0

Hello,

I would like to have the possibility to insert several entries with similar content one after the other.
For this I wanted to replace the "Create" button with two buttons: "Create" and "Create and close".
The "Create" button should create an entry but leave the form open so that I can adjust the contents of the form to create another entry.
However, with my current code there is still the problem that the form is reset after creating. Is there a way that this does not happen?

new $.fn.dataTable.Buttons(table, [
    {
        extend: 'create',
        editor: editor,
        formButtons: [
            {
                text: 'Create and close',
                className: 'btn-primary',
                action: function () {
                    this.submit();
                },
            },
            {
                text: 'Create',
                className: 'btn-secondary',
                action: function () {
                    const that = this;

                    this.submit(function () {
                        that.create();
                    }, null, null, false);
                },
            },
        ],
    },
    { extend: 'edit',   editor: editor },
    { extend: 'remove', editor: editor },
]);

Layout 'info' callback

$
0
0

I have a parent-child table. I started using Scroller and noticed that the info displayed at the bottom of the child table is really the count from the parent table!

So, I created an info callback function which sets the proper start, end and max values. As I trace (F10) through the code, I can see that it is properly displaying. However, at the end (of the tracing) it (re)displays the count from the parent table.

What am I doing wrong?

Row selection and deselection problem

$
0
0

Hey all, I am having a problem. When my user selects a datatables row, it populates variables (in external quill instances and such). If the user selects another row it will overwrite the variables. I have set up a confirm box, to prompt the user. The problem is once cancel is pressed, the new record is still highlighted. If I do this 3 times, two records are highlighted even when my select is set to single. Any suggestions? Here is relevant code:

    <script>
        var editor; // use a global for the submit and return data rendering in the examples
        var savedFirst; // prevents user from sending to printer unless document is saved

        $(document).ready(function() {
            var table2 = $('#editTable').DataTable({
                pageLength: 5,
                lengthMenu: [[5, 10, 20, -1], [5, 10, 20, 'All']],
                ajax: 'ajaxPhoneLogs.php',
                processing: true,
                language: {
                    processing: '<i class="fa-duotone fa-gear fa-spin"></i> Data Loading...',
                    searchBuilder: {
                        button: '<i class="fa-solid fa-magnifying-glass-arrow-right"></i> Refine Search',
                        title: 'Choose Filter Options'
                    }
                },
                buttons: [
                    '<i class="fa-solid fa-magnifying-glass-arrow-right"></i> Refine Search'
                ],
                columns: [
                    { data: 'phonelogs.id', visible: false, searchable: false },
                    { data: 'phonelogs.CR_ID', visible: false },
                    { data: "phonelogs.callDateTime", render: DataTable.render.datetime('M/D/YYYY, h:mm:ss a') },
                    { data: 'calltypes.name' },
                    {
                        data: null, render: function (data, type, row) {
                            return data.form.FirstName + ' ' + data.form.LastName;
                        }, searchable: false
                    },
                    { data: "phonelogs.callNotes", visible: false },
                    { data: "phonelogs.greeting", visible: false, searchable: false },
                    { data: "phonelogs.poled1", visible: false, searchable: false },
                    { data: "phonelogs.poled2", visible: false, searchable: false },
                    { data: "phonelogs.responseBody", visible: false, searchable: false },
                    { data: "phonelogs.closing", visible: false, searchable: false },
                    { data: "phonelogs.answeredBy", visible: false },
                    { data: 'PrisonFacilityListing.Prison_Name' },
                    {
                        data: "phonelogs.printed", searchable: false,
                        render: function (val, type, row) {
                            return val == 0 ? "No" : "Yes";
                        }, searchable: false
                    },
                    { data: "form.FirstName", visible: false },
                    { data: "form.LastName", visible: false },
                    { data: "form.PrisonerID", visible: false }
                ],
                select: 'single',
                order: [2, 'desc'],
            });

            var previousLog = null; // To store previous data
            var previousSelectedRow = null; // To store the previously selected row

            function isDifferentLog(log1, log2) {
                return JSON.stringify(log1) !== JSON.stringify(log2);
            }

            $('#editTable tbody').on('click', 'tr', function () {
                var newLog = table2.row(this).data();
                var currentRow = this;                
                console.log('New log selected:', newLog);

                // Check if there is previous data and the user is trying to select a new row
                if (previousLog && isDifferentLog(previousLog, newLog)) {
                    var userConfirmed = confirm("You have unsaved changes. Do you want to overwrite the previous response?");
                    if (!userConfirmed) {
                        // Deselect the new row immediately
                        $(currentRow).removeClass('selected');
                        
                        // Re-select the previous row if it exists
                        if (previousSelectedRow) {
                            $(previousSelectedRow).addClass('selected');
                        }
                        return; // Exit if the user does not confirm
                    }
                }

                // Clear previous selection
                table2.$('tr.selected').removeClass('selected');

                // Proceed with updating the data if the user confirms or there is no previous data
                $(currentRow).addClass('selected');
                previousLog = newLog; // Update the previous data with the new data
                previousSelectedRow = currentRow; // Store the current row as the previously selected row

I tried this but then I couldn't even half select the rows:

var previousLog = null; // To store previous data
var previousSelectedRow = null; // To store the previously selected row

function isDifferentLog(log1, log2) {
    return JSON.stringify(log1) !== JSON.stringify(log2);
}

$('#editTable tbody').on('click', 'tr', function () {
    var newLog = table2.row(this).data();
    var currentRow = this;
    console.log('New log selected:', newLog);

    // Check if there is previous data and the user is trying to select a new row
    if (previousLog && isDifferentLog(previousLog, newLog)) {
        var userConfirmed = confirm("You have unsaved changes. Do you want to overwrite the previous response?");
        if (!userConfirmed) {
            // Re-select the previous row and deselect the new row
            table2.rows().deselect(); // Deselect all rows
            if (previousSelectedRow) {
                table2.row(previousSelectedRow).select(); // Re-select the previous row
            }
            return; // Exit if the user does not confirm
        }
    }

    // Clear previous selection
    table2.rows().deselect();

    // Proceed with updating the data if the user confirms or there is no previous data
    table2.row(currentRow).select();
    previousLog = newLog; // Update the previous data with the new data
    previousSelectedRow = currentRow; // Store the current row as the previously selected row
});

Thanks in advance.. I can't set up a live test, but I can give you Allan access again if it is more than a simple mistake on my part.

Can I set to duplicate entire record when in Duplicate as I only have selected a few rows in edit?

$
0
0
{
    extend: 'selected',
    text: 'Duplicate',
    action: function (e, dt, node, config) {
        // Start in edit mode, and then change to create
        editor
            .edit(table.rows({ selected: true }).indexes(), {
                title: 'Duplicate record',
                buttons: 'Create from existing'
            })
            .mode('create');
    }
},

Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Datatable 2.0.7 button in layout giving error

$
0
0
new DataTable('#SpfxDatatable', {
      pageLength: 10,
      language: { "search": "Filter: " },
      retrieve: true,
      responsive: true,
      scrollCollapse: true,
      scrollY: '50vh',
      buttons: [{ text: 'Show all groups', action: function () { alert('Clicked'); }, className:'hideEmptyButton' }],
      layout: {
        topStart: {
          buttons: [
            'copy', 'excel', 'pdf'
          ]
        },
        topEnd: 'search',
        bottomStart: 'info',
        bottomEnd: 'paging'
}
    })

When i use DOM opttions all the features align left. When I try to use layouts, buttons is not available.
I am using it in a spfx solution with react and have imported all the necessary components.

import 'datatables.net-buttons-dt';
import 'datatables.net-dt/css/dataTables.dataTables.min.css';
import 'datatables.net-responsive-dt';
import DataTable from 'datatables.net-dt';

Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Export Buttons don't work in Blazor (Server App).

$
0
0

Hi, I'm using Datatable using a Blazor Server App, everything works fine except 2 points:

1- Destroy function doesn't work; as I need to bind again the datatable to another datasource with difference columns structure
2- Export buttons don't appear at all.

Please note that I have limited experience in javascript,

I appreciate your support.

Youssef

memory size error from time to time

$
0
0

Hello,

I have a datatable editor php script used for server side processing. Sometimes, especially the first time requested by the front end, it reports "Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) in ......" But after refreshing the page, it successfully responds with json data which is just around 15 kb.

Does anyone have any idea why memory size error reports the first time requested, and then works well?

Thanks.

Changing the last page number on batch loading

$
0
0

Hey all,

My current code loads a batch of the first 300 rows and shows pagenation like below:

Next batch will be loaded if users click the last page ("30") and then it will be shown like below:

Is it possible to change the last page numbers to be shown with next batch?
I.e., 30 and 60 in the above screenshots to "30-60" and "60-90".

I couldn't find how to hook the pagenation. Can anyone please help me?


Adding a Print button gives an error

$
0
0

I've tried to add a Print button using the guide... https://datatables.net/extensions/buttons/examples/print/simple.html

I've added the dependencies, but when I click the "Print" button the console shows...

buttons.print.min.js:5 Uncaught 
TypeError: Cannot read properties of undefined (reading 'map')
    at B.action (buttons.print.min.js:5:1163)
    at action (dataTables.buttons.js:748:19)
    at HTMLButtonElement.<anonymous> (dataTables.buttons.js:769:7)
    at HTMLButtonElement.dispatch (jquery-3.5.1.min.js:2:43090)
    at v.handle (jquery-3.5.1.min.js:2:41074)
action  @   buttons.print.min.js:5
action  @   dataTables.buttons.js:748
(anonymous) @   dataTables.buttons.js:769
dispatch    @   jquery-3.5.1.min.js:2
v.handle    @   jquery-3.5.1.min.js:2

This would be too big and complex to create a test case so I wondered if someone could point me in the correct direction based on the console output?

I also use Ajax to pull in the data via a CSV which might be part of the reason.

  $.ajax({
    url: "import.php",
    method: "POST",
    data: formdata,
    dataType: "json",
    contentType: false,
    cache: false,
    processData: false,
    success: function(jsonData) {
      $("#csv_file").val("");
      table = $("#datatable").DataTable({
        data: jsonData,

        buttons: [
          'print',
          {
            extend: 'colvis',
            columns: ':not(.noVis)',
            postfixButtons: ['colvisRestore'],
          },

You'll notice above I added 'print' inside "buttons" because I have other buttons. This was because if I use the syntax from the guide below it is ignored. I've also replaced the existing buttons but it's still the same problem. I have also tried 'copy', 'csv', 'excel', 'pdf', 'print' and still get the same errors.

    layout: {
        topStart: {
            buttons: ['print']
        }
    }

How to deal with tailwind css?

Export PDF problems with columnspan cell

$
0
0

Hi, i have my table that with the header divided in two column span cell: TITLE1 and TITLE2
When i try to export in pdf, what i see is the header and all <td> but no the column span cell...

https://jsfiddle.net/djzv5csb/2/

order + reorder not working

$
0
0

Greetings,

I have a simple table with the RowReorder extension.

    const tableObj = $('#seats');
    const table = tableObj.dataTable({
        paging: false,
        searching: false,
        info: false,
        rowReorder: {
            selector: 'i.sortable-handle',
        },
    });

When I click a column header to order the table, it does so, but then if I drag a row to a new order it fails and the row 'floats' back to its original order/location. There are no errors in the console.

How can I enable both order and reorder at the same time?

Change name to column

How to hide Table Information Summary when page is small?

$
0
0

This is the dom for my data table currently.

"<'row'<'col-12 col-sm-6 col-md-4 col-lg-3'l><'col-md-4 col-lg-6 d-none d-md-block'><'col-12 col-sm-6 col-md-4 col-lg-3'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-md-5 'i><'col-md-7'p>>",

I currently would like to hide <'col-md-5 'i> when the page is small. What could I add to this that would hide the column and only show the pagination?

[.net] File Upload custom action

$
0
0

In this topic https://datatables.net/forums/discussion/comment/196440/ I read this comment:

Hi Vincent,

Good to hear the patch worked - thanks for letting me know.

That particular method isn't possible I'm afraid. Instead what you need to do is update the newly created database row in your action function. You've got the id for the primary key, so something like:

editor.db().Update(
  "uploaded_files",
  new Dictionary<string, object>{
    {"web_path", myVar}
  },
  new Dictionary<string, object>{
    {"id", id}
  }
);

I am trying to do this, but it is not working, this is part of my code:

editor
.Field(new Field("CertificateId")
   .Upload(
       new Upload((file, id) => {
            var someVar = _blobStorageService.UploadBlobAsync(file.OpenReadStream(), "templates");

           editor.Db().Update(
             "Files",
             new Dictionary<string, object>{
                {"FilePath", someVar}
             },
             new Dictionary<string, object>{
                {"id", id}
             }
           );

           return id;
       })
       .Db("Files", "Id", new Dictionary<string, object>
       {
           {"FileName", Upload.DbType.FileName}
       })
       .Validator(
           Validation.FileExtensions(
               ["pdf"],
               "Alleen pdf files zijn toegestaan."))
       )
   .SetFormatter(Format.NullEmpty()));

How can I use a variable that is inside the upload action to update a field in the Files table?


Misaligned header when using scrollX and margin:auto

$
0
0

Hi there,

I have recently added a "Streamlit" component to ITables, that let Python users render their DataFrames as interactive datatables in that context - see the demo here: https://itables.streamlit.app/

For the Streamlit component I've had to set scrollX=True by default as the tables are rendered with an iframe that, unlike Jupyter Notebook outputs cells, don't have an horizontal scroll bar.

This mostly works, but when I try to center the table using margin:auto;table-layout:auto;width:auto;caption-side:bottom for the style, I get a centered table but the header remains on the left, like in the screenshot below.

Do you see how to fix that? Thanks!

data-order attr in Server side Processing

$
0
0

Without using serverside we can use data-order attribute for custom sort. I want to use it in serverside too, as I have a column where it contains mixed data sets like int, float, string. The sorting is happening by take the column as a string. So I'm getting 75 at first then getting 100.

Example : [0, 100, 75, 100, NA] is sorted desc as [75, 100, 100, 0, NA]. Sorry I cannot link a test case please don't ask for it.

DataTable refresh not being actioned

$
0
0

Error messages shown:
Normal Screen (Firefox) -

Wallboard Screen -

Description of problem:
Hi, since Tuesday morning (04JUN24) the DataTable element of our wallboards are not refreshing. These run from an IIS server as a .Net8.0 application and the application works fine in Chrome, Edge and Firefox on the desktop, and until the morning on LG Signage screens using webOS 3.3.0-23 (dreadlocks-deua). Nothing has updated on the screens and the IIS server and application are unchanged, Does anyone have any ideas?

The libraries I am using are -
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"
integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N"
crossorigin="anonymous">

<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css"
integrity="sha512-1k7mWiTNoyx2XtmI96o+hdjP8nn0f3Z2N4oF/9ZZRgijyV4omsKOXEnqL1gKQNPy2MTSP9rIEWGcH/CInulptA=="
crossorigin="anonymous"
referrerpolicy="no-referrer" />

Any help on how to try and debug this gratefully accepted!

Cheers,
David

Serverside: OR Search not working

$
0
0

Hello,

i have a datatable setup serverside, all working great except i can not get OR search working, for instance:
"Word Anotherword"
It will not look for "Word" OR "Anotherword" but for "Word Anotherword".

I have looked at multiple posts but they did not helpe me as it seems to be already be implemented what these posts suggest.

My DataTableInitiation is like this:

new DataTable('#example', { 
    "search":
        {
            "regex" : true,
            smart : false
        },
    ajax: 'php/xxxx.php',
    columns: [      
        { data: 'xxx', "regex":true }
    ],  
    processing: true,
    serverSide: true,
;

I do have a search for every column which calls this:

column.search(input.value, true, false).draw();

The Payload also looks fine to me:
(EDIT: gave column payloard first)

start: 0
length: 10
search[value]: ges kla
search[regex]: true

The php script seems to already have the functionality but i still get 0 results:

if ( count( $globalSearch ) ) {
            $where = '('.implode(' OR ', $globalSearch).')';
        }

        if ( count( $columnSearch ) ) {
            $where = $where === '' ?
                implode(' AND ', $columnSearch) :
                $where .' AND '. implode(' AND ', $columnSearch);
        }

        if ( $where !== '' ) {
            $where = 'WHERE '.$where;
        }

        return $where;

There is only one custom change i made to the sspclass, which is hardcoded the max amount of data output with the max_items variable im passing, but if i understood correctly this should not be the issue as it gets applied after the sql search:

return array(
            "draw"            => isset ( $request['draw'] ) ?
                intval( $request['draw'] ) :
                0,
                "limit" => $limit,
            "recordsTotal"    => intval( $recordsTotal ),
            "recordsFiltered" => intval( $recordsFiltered ),
            "data"            => self::data_output( $columns, $data, $max_items)
        );

I hope youre not annoyed, but all the posts did not help me yet.
Thanks in advance.

DataTables Editor v1.6.5 error Cannot read properties of undefined (reading 'select')

$
0
0

Hi Alan and Kevin,

Last year around this time we worked on a application that allowed our sales team to do their yearly budget.
They application was well received and it is that time of year again, however when I dusted off the application and was testing out functionality I received an error when using the DataTable Editor function. ( this worked last year)

Cannot read properties of undefined (reading 'select')
js salespersonBillTo_editor.on('open', function () { $('div.DTE input')[0].select(); });

I receive the error when I click on any cell in the Next Years Budget row .

As luck would have it I found a forum thread from last year with a bin where we work on this particular area of the script.

https://datatables.net/forums/discussion/76556/expanding-all-child-rows-from-button#latest

I created a new bin https://live.datatables.net/falecabi/1/edit with the latest code that was working last year, however I'm getting some errors the bin and it does not show the to show budgetDataSet row records.

My scripts does work in production( see image below) and this is not the issue I am currently having, just need some help with the bin.

Once we can get the budget data to show in the bin, then perhaps we can recreate the "Cannot read properties of undefined (reading 'select')" error

Viewing all 82410 articles
Browse latest View live


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