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

Finding number of matches per row from search/filter API

$
0
0

Hi all,

I've been using DataTables for years now and it's an essential part of my toolbox! Amazingly useful.

I'm currently building in a filter which works well but I'm trying to get the following information from it so I can construct a way to organise the rows based on the result. Here goes:

When a filter/search is performed (I supply it regex), I would like to hook in somewhere and return the number of matches per row/column so I can score the row based on this and the rows with the most number of matches for the words searched will bump to the top of the table.

So for example, in this case, the user has typed in a new idea. I've cleaned out some stop words then I pass the cleaned string to the filter/search as regex. It's found 4 items which contain any of the words "Supplier", "Nice" or "Approved".

The 4th result (bottom row) has been matched with "Supplier" 3 times and "Approved" 1 time so a total of 4 matches.

The other rows have fewer matches.

I'll be just fine coding the way it handles the results but the only bit of info I need is the total number of matches per row so I can score them and sort the table appropriately.

I could write a function to search the table and do this but then I'm going to be doing 2 searches effectively.

The command I am running is:
itemTable.search(newSearchString, true, false).draw();

as an example the newSearchString would look like:

**\b(?:Supplier|nice|approved) **

Here is an example of the code in action:

live.datatables.net/cidofola/1/edit

Thank you in advance for any help/pointers :smile:

Rixy


exportOptions format and call default function

$
0
0

HI everybody,

I want the exportOptions format body to export the value of an input when there is an input and call the default behavior (strip HTML tag) when there is no input.

var buttonCommon = {
        exportOptions: {
            format: {
                body: function ( data, row, column, node ) {
                    var val = $(node).find('input:not([type=hidden])').val();

                    // when val is undefined i want to call default exportOptions.format.body() ????
                    return (val === undefined)? data : val; 
                }
            }
        }
    };

I don't want to copy the default function strip in my own code because it can change in a next version of datatable.
Is it possible to do that or i have to copy the default function strip in my own code?

var strip = function ( str ) {
        if ( typeof str !== 'string' ) {
            return str;
        }
        // Always remove script tags
        str = str.replace( /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '' );

        // Always remove comments
        str = str.replace( /<!\-\-.*?\-\->/g, '' );

        if ( config.stripHtml ) {
            str = str.replace( /<[^>]*>/g, '' );
        }

        if ( config.trim ) {
            str = str.replace( /^\s+|\s+$/g, '' );
        }

        if ( config.stripNewlines ) {
            str = str.replace( /\n/g, ' ' );
        }

        if ( config.decodeEntities ) {
            _exportTextarea.innerHTML = str;
            str = _exportTextarea.value;
        }

        return str;
    };

Any help is much appreciated

Ajax call asp.net api for to long

$
0
0

Link to test case:
First call on the api on the back end using datatable is okay
When trying to Call again the api for the second time it takes to long passing in the api
and third, fourth and etc is okay no problem
Debugger code (debug.datatables.net):
Front end

 table = $('#tblServiceNumbersContent').DataTable({
            "responsive": true,
            "dom": '<"top"pl>rt<"bottom"fi><"clear">',
            "searching": false,
            "ordering": false,
            "bInfo": false,
            "lengthChange": false,
            "pageLength": 1000,
            language: {
                processing: '<i class="fa fa-spinner fa-spin fa-2x fa-fw"></i>',
                paginate: {
                    next: '>', // or '→'
                    previous: '<' // or '←' 
                }
            },
            "columnDefs": [
                //Added classes in Dom
                { "className": "service-number-charges", "targets": [2] },
                { "className": "service-number", "targets": [1] },
            ],
            "processing": true,
            "serverSide": true,
            "async": true,
            //"deferLoading": 1000,
            //"scrollX": true,
            "deferRender": true,
            //searchDelay: 1500,
            "ajax":
            {
                "url": "expensemanagement.aspx/GetServiceNumbersFromTicketDetailsDataTable",
                "contentType": "application/json",
                "type": "POST",
                "dataType": "JSON",
                "data": function (d) {
                    //setting up Paramaters for APi 
                    //run_waitMe('facebook', 'tblServiceNumbersContentBody', 'Loading...');
                    console.log("sent")
                    var param = JSON.stringify({
                        ticketId: ticketId,
                        draw: d.draw,
                        offsetRow: d.start,
                        fetchRow: d.length,
                        searchCriteria: $('#serviceNumberContentFilter').val(),
                        IsShowMissingSN: DataService.IsShowMissingSn
                    });
                    return param;
                },
                "dataSrc": function (json) {
                    //Receive from the APi 
                    console.log("response");
                    DataService.SavedServiceNumbersTicketDetails = json.d.serviceNumberResult;
                    json.draw = json.d.draw;
                    json.recordsTotal = json.d.recordsTotal;
                    json.recordsFiltered = json.d.recordsFiltered;
                    json.data = json.d.data;         

                    if (json.data.length > 0) {


                        $('#import').hide();
                        $('#importXml').hide();
                        $('#genericImport').hide();
                        $('#append').removeClass('hidden');

                        //for (var i = 0; i < json.d.data.length; i++) {
                        //    commonService.toCurrency(json.d.data[i].ChargeAmount);
                        //}
                        commonService.toCurrency(json.d.TotalChargeAmount); 
                        
                    } else {
                       // $('#tblServiceNumbersContent_processing').removeClass('dataTables_processing');
                        $('#expense-management-window').waitMe('hide');
                        $('#tblServiceNumbersContentBody').waitMe('hide');

                        return [];
                    }

                    $('#expense-management-window').waitMe('hide');
                    $('#tblServiceNumbersContentBody').waitMe('hide');

                    //loadHideColumns(table);
                    totalChargeAmount = parseFloat(json.d.TotalChargeAmount);

                    var return_data = json;
                    return return_data.data;
                },
                "beforeSend": function () {
                    console.log("before")
                    // Here, manually add the loading message.
                    $('#tblServiceNumbersContent > tbody').html(
                        '<tr class="odd">' +
                        '<td valign="top" colspan="6" class="dataTables_empty">Loading&hellip;</td>' +
                        '</tr>'
                    );
                }
            },
            "columns": [
                { "data": "Multiple" },
                { "data": "ServiceNumber" },
                { "data": "ChargeAmount" },
                { "data": "ActionDisplay" }
            ],
            "action": function (e, dt, node, config) {
                var data = oTable.rows({ selected: true }).data();
                console.log("data---" + data);
            },
            "fnDrawCallback": function () {
                //After Display
                $('#tblServiceNumbersContent').css('width', '');
                //Hide Column 1
                $("#tblServiceNumbersContent tbody tr td:nth-child(1)").css("display", "none");
                $("#tblServiceNumbersContent thead tr th:nth-child(1)").css("display", "none");
                displayServiceNumbersFooter();
                $.fn.DataTable.ext.pager.numbers_length = 6;

                var pageLenght = this.fnPagingInfo().iTotal;

                // if the list is more than 1001 
                if (pageLenght < 1001) {
                    $('.dataTables_paginate').hide();
                    document.getElementById("service-number-content").style.position = null;
                    document.getElementById("service-number-content").style.top = null;
                } else {
                    $('.dataTables_paginate').show();
                    document.getElementById("service-number-content").style.position = "relative";
                    document.getElementById("service-number-content").style.top = "-40px";
                }

                $('#serviceNumberTotal').html(commonService.toCurrency(totalChargeAmount));

                table.settings()[0].jqXHR.abort();

            },
            "createdRow": function (row, data, dataIndex) {

                //Creating row individual
                if (data.InventoryId != 0) {
                    if (data.Status) {
                        $(row).addClass('row-inactive');
                    } else {
                        // <tr>
                    }             
                } else {
                    $(row).addClass('row-invalid');
                }

                $(row).find('td:nth-child(4)').addClass('text-center');
            }
        });

**Back end**

  [WebMethod]
        public static object GetServiceNumbersFromTicketDetailsDataTable(int ticketId, int draw, int offsetRow = 0, int fetchRow = 50, string searchCriteria = "",bool IsShowMissingSN = false)
        {
            var repo = new ServiceNumbersRepo();
            var serviceNumberDataTableReqDTO = new ServiceNumberDataTableReqDTO();
            var count = 0;

            var result = repo.GetServiceNumbersFromTicketDetailsDataTable(ticketId, draw, offsetRow, fetchRow, searchCriteria, IsShowMissingSN);

            //if (IsShowMissingSN)
            //{
            //    result = result.Where(x => x.InventoryId == 0 || x.InventoryId == null).ToList();
            //}

            var totalAmount = repo.GetServiceNumbersFromTicketDetails_TotalChargeAmount(ticketId);
            serviceNumberDataTableReqDTO.draw = draw;
            serviceNumberDataTableReqDTO.data = FilteredServiceNumbersTicketDetails(result);
            serviceNumberDataTableReqDTO.serviceNumberResult = result;
            serviceNumberDataTableReqDTO.TotalChargeAmount = totalAmount;

            if (string.IsNullOrWhiteSpace(searchCriteria))
            {
                count = repo.GetServiceNumbersFromTicketDetailsCount(ticketId, IsShowMissingSN);
                serviceNumberDataTableReqDTO.recordsFiltered = count;
                serviceNumberDataTableReqDTO.recordsTotal = count;
            }
            else
            {
                var withoutOffSetCount = repo.GetServiceNumbersFromTicketDetailsCountWithoutOffset(ticketId, searchCriteria, IsShowMissingSN);

                serviceNumberDataTableReqDTO.recordsFiltered = withoutOffSetCount;
                serviceNumberDataTableReqDTO.recordsTotal = withoutOffSetCount;
            }

            return serviceNumberDataTableReqDTO;


        }

Error messages shown:
No error but takes to long to call on the api
Description of problem:
Having a problem calling for the second time on the api using datatable

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

when i try to implement the inline edit function it is giving me this error

Заметка id11 о Русские Силачи - Ленгвизд - LiveJournal

$
0
0

Это чревато еще более серьезными гормональными нарушениями, физиологическими и психологическими проблемами. С детства Гаак тренировался: прыгал в длину на 4 м 90 см, в высоту с места - на 1 м 40 см, 180 м пробегал за 26 с. Спортивная индустрия при производстве спортивного инвентаря широко использует новейшие достижения научно-технического прогресса, благодаря которому, может возникнуть ситуация, когда спортсмен побеждает не благодаря своим физическим и интеллектуальным способностям или возможностям, а благодаря тому, что у него есть инвентарь, которого нет у соперников. Спортсмены принимают его с утра.
Начинайте день с силовых упражнений с гантелями. Сбалансировать этот процесс можно исключением жареного, жирного из рациона, кардио тренировками, употреблением льняного масла, ниацина.
Затем идет плато, на котором Вы держите одну и ту же дозировку в 2-3 недели. Основываясь как второстепенное событие во время карнавалов в Северной Америке, рестлинг постепенно перерос в нечто самостоятельное, в обособленный жанр развлечения.
Перейдите по <a href="https://farm-shop.su/2020/01/20/lechenie/kakoj-tip-lechenija-vypadenija-volos-mne-podhodit/">детальнее на сайте</a>
Для очистки организма от токсинов, восстановления желудочно-кишечного тракта, работы и функций печени рекомендуется принимать порошок Расторопши.
Программу стероидов не рекомендуется использовать лицам до 20 лет. Practical medicine. - 2014. Обнаружено, что одновременное использование двух стероидов в умеренных дозах может оказаться весьма эффективным и безопасным.

За исключением типа жизненной силы, которую они получают после использования Винстрола, они будут выглядеть пухлыми, увеличивая толщину кости и вес. Купите Винстрол Великобритания - форма анаболического стероида, открытого в нескольких явных методиках организации; В конце концов, в конце концов он стал действительно безошибочным, чтобы дать несущественное краткое изложение потенциальных основных факторов. Винстрол - это стероид, который дает именно такое разрешение, которое требуется мышечной голове. Чтобы быть плодотворным боссом, важно, чтобы у мускулистой головы была потрясающая мера выносливости, настойчивости и самоконтроля. Я верю, что Ubuntu linux великолепна. Когда вы никоим образом не использовали Ubuntu раньше, это, вероятно, будет простым введением, поскольку вам не придется устанавливать его самостоятельно. Этот браузер позволит встроенной программе запуска приложений Google работать вместе с вашей системой Ubuntu, так что ваша система станет похожей на Chromebook на стероидах. В то время как мужчины вырабатывают практически в десять раз больше тестостерона, чем девушки, требуется достаточное количество этого гормона класса андрогенов для поддержания правильной эндокринной системы. Вместо значительного повышения уровня тестостерона, тренировка повысит чувствительность образованной мышцы к тестостерону.

Image is not Refreshing after Update. Data Table Shows me the Previous Image Till page get refreshed

$
0
0

Image is not Refreshing after Update. Data Table Shows me the Previous Image Till page get refreshed by (Ctrl + F5)

The following is my DataTable Load Function. Below the Function I have Pasted my Insert and Update Ajax Call Function. In that function I Called this function After Updated the Images. But the DataTable Remains the Same Image till the Page Gets Refreshed by (Ctrl + F5)

var ModuleNametable;  // Global Declaration

function fnLoadModuleTable() {

            if ($.fn.DataTable.isDataTable('#tblModuleNameDetails')) {
                    ModuleNametable.destroy();
            }

            jQuery.ajax({
                url: '../api/MasterManagementAPI/fnGetModuleNameList',
                type: 'POST',
                data: {
                },
                success: function (response) {

                        ModuleNametable = $('#tblModuleNameDetails').DataTable({
                            data: response,
                            'scrollY': 300,
                            columns: [
                                {
                                    'data': 'ModuleID',
                                    'searchable': false,
                                    'orderable': false,
                                    'visible': false
                                },
                                {
                                    'data': 'ModuleImage',
                                    'render': function (data) {
                                        return '<img src="' + data + '" width="50" height="50" />'
                                    }
                                }
                            ],
                            lengthMenu: [[5, 10, 50, -1], [5, 10, 50, "All"]],
                            select: {
                                style: 'single'
                            }
                        })
                            .on('select', function (e, dt, type, indexes) {

                            })
                            .on('deselect', function (e, dt, type, indexes) {

                            });
                }

            });
}

function InsertUpdateModule ()
{
jQuery.ajax({
                url: '../api/MasterManagementAPI/fnInsertUpdateModuleNameMaster',
                type: 'POST',
                data: {

                },
                success: function (response) {

                        var newData = new FormData();
                        var files = $("#fileModuleImage").get(0).files;
                        if (files.length > 0) {
                            newData.append("FileData", files[0]);
                            newData.append("ModuleID", objResponse[1] );
                        }

                        if (files.length > 0) {    //   upload the profile picture
                            jQuery.ajax({
                                url: '../api/MasterManagementAPI/fnModuleMasterImageUpload',
                                type: 'POST',
                                data: newData,
                                contentType: false,
                                processData: false,
                                beforeSend: function (xhr) { $('body').append("<div id='loading'></div>"); },
                                success: function (response) {
                                    $("#loading").remove();
                                    if (response == 'SUCCESS') {
                                        alert('ImageUploaded Successfully');
                                    }
                            });
                        }
     // HERE I CALLED MY DATATABLE LOAD FUNCTION BUT IT'S NOT SHOWING ME THE LATEST UPLOADED IMAGE

                       fnLoadModuleTable();
                    }
                }
            });
}

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

Since I purchased the Editor, it doesn't work any more.

$
0
0

Hi

Since I purchased the editor, some things don't work any more

My code code seems to be very simple :

$(document).ready(function() {
    editor = new $.fn.dataTable.Editor( {
        ajax : "ajaxserver.php?context=editcontact&userid=<?php echo $_SESSION["userid"]; ?>",
        table: "#PartnersTable",
        fields: [ 
            {label: "Nom:",             name: "Name"}, 
            {label: "Addresse:",        name: "Address" },
            {label: "Code postal:",     name: "CPos" }, 
            {label: "Ville:",           name: "City"  }, 
            {label: "Téléphone 1:",     name: "Phone1"  }, 
            {label: "Téléphone 2:",     name: "Phone2" },
            {label: "Email:",           name: "Email" }
        ]
    } );
 
    $('#PartnersTable').DataTable( {
        dom: "Bfrtip",
        ajax: "ajaxserver.php?action=getcontactlist",
        columns: [
            { data: "Name" },
            { data: "UserName" },
            { data: "Address" },
            { data: "CPos" },
            { data: "City" },
            { data: "Phone1" },
            { data: "Phone2" },
            { data: "Email" },
            { data: "Dep" },
            { data: "Status" },
            { data: "RecallDate" }
        ],
        select: true,
        buttons: [
            
            { extend: "edit",   editor: editor },
            { extend: "remove", editor: editor }
        ]
    } );

The two things that don't work any more are (at least) :

select: true, ---> doesn't have effect
{ extend: "edit", editor: editor }, -> button doesn't appear
{ extend: "remove", editor: editor } -> button doesn't appear

Please not that :

  • The datatable widget works fine, except the "select : true" option
  • It worked with the trial version
  • I don't have any error message in the console

Can you help me?
Regards.

Input not valid

$
0
0

Hello,

I encounter a strange phenomenon.
When I do an Update by Datatable Editor inline so directly in the table it works well.
But when I select the line to be modified and I click on Update (the Modal appears) I modify my line and I click on the update button, I get an error message: Input not valid.

Console :
Requete :

        
    action  "edit"
    data[row_17][r_i_d_a][id]   "17"
    data[row_17][r_i_d_a][perimetre]    "3"
    data[row_17][r_i_d_a][clients]  "13"
    data[row_17][r_i_d_a][activite] "1"
    data[row_17][r_i_d_a][date_decision]    "2019-02-22"
    data[row_17][r_i_d_a][i_d_a]    "A"
    data[row_17][r_i_d_a][problemes]    "DATAMATRIX+Traçabilité++produit,+POKA+YOKE+mélange+réf,+manquant+pièces"
    data[row_17][r_i_d_a][criticite_rida]   "1"
    data[row_17][r_i_d_a][solutions]    "Modification+des+MOP+"
    data[row_17][r_i_d_a][date_deadline]    "2019-03-31"
    data[row_17][r_i_d_a][etat_avancement]  "-505"
    data[row_17][r_i_d_a][status]   "5"
    data[row_17][r_i_d_a][etat] "1"
    data[row_17][r_i_d_a][users]    "1"
    data[row_17][r_i_d_a][commentaire]  "Attente+retour."
    data[row_17][r_i_d_a][date_realisation] ""
    data[row_17][r_i_d_a][date_verification]    ""
    data[row_17][r_i_d_a][resultat] ""

Response :

    
    fieldErrors [ {…} ]
    0   Object { name: "r_i_d_a.id", status: "Input not valid" }
    name    "r_i_d_a.id"
    status  "Input not valid"
    data    []

View : {"fieldErrors":[{"name":"r_i_d_a.id","status":"Input not valid"}],"data":[]}

L'update not work !

But the same operation by InLine Editor :
Console :
Requete :

    action=edit&data%5Brow_17%5D%5Br_i_d_a%5D%5Bcommentaire%5D=Attente+retour+Client.

Response :

    
    data    [ {…} ]
    0   Object { DT_RowId: "row_17", r_i_d_a: {…}, perimetre_rida: {…}, … }
    DT_RowId    "row_17"
    r_i_d_a Object { perimetre: "3", clients: "13", activite: "1", … }
    perimetre   "3"
    clients "13"
    activite    "1"
    date_decision   "2019-02-22"
    i_d_a   "A"
    problemes   "DATAMATRIX Traçabilité produit, POKA YOKE mélange réf, manquant pièces"
    criticite_rida  "1"
    solutions   "Modification des MOP "
    date_deadline   "2019-03-31"
    id  "17"
    etat_avancement "-505"
    status  "4"
    etat    "1"
    users   "1"
    commentaire "Attente retour Client."
    date_realisation    null
    date_verification   null
    resultat    ""
    perimetre_rida  Object { nom_perimetre: "Reconditionnement" }
    nom_perimetre   "Reconditionnement"
    client_rida Object { nom_client: "XXX" }
    nom_client  "XXX"
    activite_rida   Object { nom_activite: "Automotive" }
    nom_activite    "Automotive"
    tech_compteur_modif_deadline    Object { compteur: null }
    compteur    null
    status  Object { nom_status: "Suspendu" }
    nom_status  "Suspendu"
    images  Object { nom_images: "OK" }
    nom_images  "OK"
    users_rida_egale_un Object { trigramme_users_rida: "OGR" }
    trigramme_users_rida    "OGR"

L'update work perfectly!

Do you have an idea please?

Thanking you.


Some SQL tables

$
0
0

Hello, does anyone have a good example of using an editor with multiple tables (3+, when there is a main table and several side ones that are connected by one field, when there may be a lot of duplicate information, I mean one to many relationship, etc.). I saw an example on the site, but it doesn't quite fit. Thanks for your attention.

Editor Trial Question

$
0
0

I am evaluating datatables editor.
I have done some tests against a mysql database in localhost and I have followed that it works well, but I have passed it to a hosting server and there only adding records works.
Edit and Delete buttons both give this error:

Uncaught Unable to automatically determine field from source. Please specify the field name. For more information, please refer to https://datatables.net/tn/11

Does the 15-day trial version have any limitations?

-----------Debug information--------
I put this code in Button edit action:

                        var rowData = dt.row({selected:true}).data();

                        console.log ('rowData: ');

                        str = JSON.stringify(rowData);
                        str = JSON.stringify(rowData, null, 4); // (Optional) beautiful indented output.
                        console.log(str); // Logs output to dev tools console.

And the result are:

rowData:

 {
    "DT_RowId": "row_4",
    "actividades": {
        "id": "4",
        "actividad": "Patinaje 1",
        "maximo": "1",
        "dias": "12",
        "color": "#ffffff",
        "F_ACTIVA_DESDE": "2020-08-01 01:38:13",
        "F_ACTIVA_HASTA": "2020-08-31 12:00:00"
    },
    "info": {
        "ya_asignadas": "0",
        "diferencia": "1"
    }
}

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

i18n plugin file naming

$
0
0

I raised a question a few years ago about using BCP 47 language tags for the various translations. (The issue has since been closed, which is why I've raised a new discussion.) I don't know if you've had any more thoughts about it?

If it's difficult, for backward compatibility reasons, to rename the files, it would still be a great help if the BCP 47 tag could be inserted somewhere in the file contents please, even initially just for any new translations. It would not only help developers, who just want to know what the language is, but would also help future updaters of the language files who might need to differentiate between versions of a language (eg fr-FR and fr-CA or de-DE and de-AT).

Thanks.

Jquery datatable child table Page length selection not working

$
0
0

Hello everyone, i am facing an issue i am adding a one table. table have right side plus button that is used to append child table. when i add child everything perfectly fine. child pagination sorting work as expected but. child page length dropdown unable to select the page length change option. i don't know what happen. i have attached the snapshot

DevTools failed to load SourceMap

$
0
0

I get the message DevTools failed to load SourceMap: Could not load content for http://.../.../datatables/pdfmake.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE in Chrome Developer Tools when I use the minified version of DataTables, but not when I use the unminified version. I am using the latest versions of DataTables.

Any ideas?

[pdfmake] warning failed to load SourceMap

$
0
0

Hi,

I'm testing pdfmake v 0.1.36

I'm getting this warning
DevTools failed to load SourceMap: Could not load content for ....pdfmake/pdfmake.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE.

This was not present in older version, anyone have a fix for this?

I have opened an issue on github
https://github.com/DataTables/Plugins/issues/486

Can't apply changes to multiple Datatables

$
0
0

Hello Community! I'm discovering this amazing tool, and I'm struggling for days to make my code work, I would like to have multiple data tables in the same web page, but my code display perfectly the first table, and don't apply the "columnDefs" changes to the others, here is my function:

if ( $.fn.dataTable.isDataTable( '.example' ) ) {
    table = $('.example').DataTable();
     }
    else {
    table = $('.example').DataTable( {
        "columnDefs": [ {"className": "dt-left", "targets": "_all"}  ]
    } );
    }

I can't afford a complete test case, but I do really need your help, Thank you in advance.

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


Using DataTables With Sharepoint

$
0
0

Hello, so I have been having issues with appending a DataTable on my landing page. I am pulling from three separate lists on different subsites through SharePoint. I will attach my code below. The weird part about it is I can get it to work perfectly if the data is static (of course...) but I will link a JSFiddle with the static data that works.

<html>
<head>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<title><strong>X, DAR-Q, & Z Deliverables</strong></title>
</head>
<body>
    <div class="container">
      <h4 class="text-center">X, DAR-Q, & Z Deliverables</h4>
        <table class = "display">
            <thead>
              <tr>
                <th>Program</th>
                <th>Deliverable</th>
                <th>To</th>
                <th>Date</th>
                <th>Approved</th>
                <th>Notes</th>
              </tr>
            </thead>
            <tbody>
            </tbody>
        </table>    
    </div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script>
function loadData(source, url) {
  return fetch(url, { headers: { accept: "application/json; odata=verbose" } }) // make request
    .then((r) => {
      if (!r.ok) throw new Error("Failed: " + url);  // Check for errors
      return r.json();  // parse JSON
    })
    .then((data) => data.d.results) // unwrap to get results array
    .then((results) => {
      results.forEach((r) => (r.source = source)); // add source to each item
      return results;
    });
}

window.addEventListener("load", function () {
  Promise.all([
    loadData("XDeliverables", "/_api/web/lists/getbytitle('XDeliverables')/items?$select=Program,To,Date,Approved,Notes"),
    loadData("YDeliverables", "/_api/web/lists/getbytitle('YDeliverables')/items?$select=Program,To,Date,Approved,Notes"),
    loadData("ZDeliverables", "/_api/web/lists/getbytitle('ZDeliverables')/items?$select=Program,To,Date,Approved,Notes"),
  ])
    .then(([r1, r2, r3]) => {
      const objItems = r1.concat(r2,r3);
      var tableContent =
        '<table id="deliverablesTable" style="width:100%" border="1 px"><thead><tr><td><strong>Program</strong></td>' +
        "<td><strong>To</strong></td>" +
        "<td><strong>Date Submitted</strong></td>" +
        "<td><strong>Approved</strong></td>" +
        "<td><strong>Notes</strong></td>" +
        "</tr></thead><tbody>";

      for (var i = 0; i < objItems.length; i++) {
        tableContent += "<tr>";
        tableContent += "<td>" + objItems[i].Program + "</td>";
        tableContent += "<td>" + objItems[i].To + "</td>";
        tableContent += "<td>" + objItems[i].Date + "</td>";
        tableContent += "<td>" + objItems[i].Approved + "</td>";
        tableContent += "<td>" + objItems[i].Notes + "</td>";
        tableContent += "</tr>";
      }
      $(tableContent).appendTo("#deliverables").DataTable();
    })
    .catch((err) => {
      alert("Error: " + err);
      console.error(err);
    });
});
</script>
</body>

Get Row ID as default for form data

$
0
0

I currently have a page setup to enter notes about a transaction. This is 2 tables. A note table and an invoice table. The note table has 3 columns. ID, inv_id, note.

How can I get the form to auto-populate the row ID in the form to submit to the note table?

    $(document).ready(function() {
        var editor = new $.fn.dataTable.Editor({
            ajax: 'php/table.id.php',
            table: '#idRequest',
            fields: [
                {
                    "label": "Notes:",
                    "name": "daily_notes.note",
                    "type": "textarea",

                },
                {
                    "label": "Note ID:",
                    "name": "daily_notes.note_id",
                    "type": "readonly",
                    "def": "disc_rq_activations.ID", <----- I know this doesnt work. 

                },


            ]
        });

Using template does not use the column render function

Scroller 2.0.2 doesn't work properly with Search Panes

$
0
0

Link to test case:

https://codepen.io/MadBoyEvo/pen/dyMNypY

If you change scrollerr to 2.0.1 it works fine

Debugger code (debug.datatables.net):
Error messages shown:

jquery-3.5.1.min.js:2 jQuery.Deferred exception: Cannot read property 'scroller' of null TypeError: Cannot read property 'scroller' of null
    at HTMLTableElement.<anonymous> (https://cdn.datatables.net/scroller/2.0.2/js/dataTables.scroller.min.js:26:93)
    at HTMLTableElement.dispatch (https://code.jquery.com/jquery-3.5.1.min.js:2:43090)
    at HTMLTableElement.v.handle (https://code.jquery.com/jquery-3.5.1.min.js:2:41074)
    at Object.trigger (https://code.jquery.com/jquery-3.5.1.min.js:2:71513)
    at HTMLTableElement.<anonymous> (https://code.jquery.com/jquery-3.5.1.min.js:2:72108)
    at Function.each (https://code.jquery.com/jquery-3.5.1.min.js:2:2976)
    at S.fn.init.each (https://code.jquery.com/jquery-3.5.1.min.js:2:1454)
    at S.fn.init.trigger (https://code.jquery.com/jquery-3.5.1.min.js:2:72084)
    at t (https://nightly.datatables.net/js/jquery.dataTables.min.js:77:155)
    at S.fn.init.za (https://nightly.datatables.net/js/jquery.dataTables.min.js:73:1) undefined
S.Deferred.exceptionHook @ jquery-3.5.1.min.js:2
jquery-3.5.1.min.js:2 Uncaught TypeError: Cannot read property 'scroller' of null
    at HTMLTableElement.<anonymous> (dataTables.scroller.min.js:26)
    at HTMLTableElement.dispatch (jquery-3.5.1.min.js:2)
    at HTMLTableElement.v.handle (jquery-3.5.1.min.js:2)
    at Object.trigger (jquery-3.5.1.min.js:2)
    at HTMLTableElement.<anonymous> (jquery-3.5.1.min.js:2)
    at Function.each (jquery-3.5.1.min.js:2)
    at S.fn.init.each (jquery-3.5.1.min.js:2)
    at S.fn.init.trigger (jquery-3.5.1.min.js:2)
    at t (jquery.dataTables.min.js:77)
    at S.fn.init.za (jquery.dataTables.min.js:73)

Description of problem:

Tried adding Search Panes and upgrading libs at the same time. Using following js

"https://nightly.datatables.net/js/jquery.dataTables.min.js"
"https://cdn.datatables.net/autofill/2.3.5/js/dataTables.autoFill.min.js"
"https://cdn.datatables.net/buttons/1.6.3/js/dataTables.buttons.min.js"
"https://cdn.datatables.net/buttons/1.6.3/js/buttons.colVis.min.js"
"https://cdn.datatables.net/buttons/1.6.3/js/buttons.html5.min.js"
"https://cdn.datatables.net/buttons/1.6.3/js/buttons.print.min.js"
"https://cdn.datatables.net/colreorder/1.5.2/js/dataTables.colReorder.min.js"
"https://cdn.datatables.net/fixedcolumns/3.3.1/js/dataTables.fixedColumns.min.js"
"https://cdn.datatables.net/fixedheader/3.1.7/js/dataTables.fixedHeader.min.js"
"https://cdn.datatables.net/keytable/2.5.2/js/dataTables.keyTable.min.js"
"https://cdn.datatables.net/responsive/2.2.5/js/dataTables.responsive.min.js"
"https://cdn.datatables.net/rowgroup/1.1.2/js/dataTables.rowGroup.min.js"
"https://cdn.datatables.net/rowreorder/1.2.7/js/dataTables.rowReorder.min.js"
"https://cdn.datatables.net/scroller/2.0.2/js/dataTables.scroller.min.js"
"https://cdn.datatables.net/searchpanes/1.1.1/js/dataTables.searchPanes.min.js"
"https://cdn.datatables.net/select/1.3.1/js/dataTables.select.min.js"
"https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"
"https://cdn.datatables.net/plug-ins/1.10.20/sorting/datetime-moment.js"

Also if you click on Search Panes button in 1st table the pane isn't displayed properly.

Has Group By been added to editor?

$
0
0

I need to group some of my table data. I read back in 2017 it was not available. Has this been implemented? I need to group my notes by note_id so it will show all notes for that ID.

Thanks

Viewing all 82269 articles
Browse latest View live


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