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

Datatable Server Side in Angular doesn't populate table properly

$
0
0

Hey everyone,

I'm rather new with datatables and have been searching for an answer to this issue. I've got a datatable in my angular project that is using server side processing to get/filter the data. On first call, the table is populated but still keeps the "No matching records found" at the bottom of the table.

When I filter results using an external dropdown and resend the parameters to the table and redraw it, the table is not populated even though I receive an answer with data inside. When I use the arrows for ordering the table or click on the pagination, the table is then populated.

There are some filters that are passed through the URL, so the issue isn't the data itself, but the rendering of the table. I receive all the results properly, I just can't seem to display them properly.

Here is the relevant code pieces:

export class AllLeadsComponent implements OnInit {



  //Datatables
  dtOptions: any = {};
  dtTrigger = new Subject();
  @ViewChild(DataTableDirective)
  dtElement: DataTableDirective;
}
  ngOnInit() {

      this.dtURL = this.hc.getUrl('customers/datatable', this.params);
      this.finalurl = `${this.envUrl.urlAddress}/${this.dtURL}`;

      this.dtOptions = {
        //retrieve: true,
        //ordering: true,
        //autoWidth: true,
        //destroy: true,
        paging: true,
        pagingType: 'full_numbers',
        pageLength: this.params.pageSize,
        serverSide: true,
        processing: true,
        dom: 'rtp',
        ajax: (dataTablesParameters: any, callback) => {
          this.http.post<DataTablesResponse>(this.finalurl, dataTablesParameters, {}).subscribe(resp => {
            this.customers = resp.data;
            this.total = resp.recordsTotal;
            callback({
              recordsTotal: resp.recordsTotal,
              recordsFiltered: resp.recordsFiltered,
              data: []
            });
          });
        },
        columns: [{ data: 'checkbox' }, { data: 'c.id' }, { data: 'c.name' }, { data: 'c.phone' }, { data: 'c.email' }, { data: 'c.source' }, { data: 'c.course' }, { data: 'i.institution' }, { data: 'c.time' }, { data: 'c.status' }, { data: 'u.name' }, { data: 'c.updated' }],
      }
    })
}

An example filter:

  onInstitutionChange() {
    this.params['filterByInst'] = 'inst_id';
    this.dtURL = this.hc.getUrl('customers/datatable', this.params);
    this.finalurl = `${this.envUrl.urlAddress}/${this.dtURL}`;
    this.rerender();
  }

The re-render:

  rerender(): void {
    try {
      this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
        dtInstance.destroy();
        this.dtTrigger.next();
      });
    } catch (err) {
      console.log(err);
    }
  }

A sample result from my network:

A sample of the table showing as empty but has data. If I click on the pagination the table will then show the results:

Any help would be highly appreciated!


DataTable Reload

$
0
0

Good morning, I don't have a very good english so excuse me.

Well I'm trying to do something for the job, where I need a Table made with the DataTable library to be constantly updating for example every 10 seconds.

I'm facing very boring problems, what I'm trying to do is give a Reload on api, as described on the official website here: https://datatables.net/reference/api/ajax.reload()

I'm using this:

function AutoReload1()
{
    var table = $('#OperationFix').DataTable({
        ajax: "data.json"
    });

    setInterval(function () {
        table.ajax.reload();
    }, 5000);

    //loadOrdersFix();
    //alert('Testing')

}

Then he returns the following error to me:

DataTables warning: table id=OperationFix - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3

Datatable Server Side in Angular doesn't show results

$
0
0

Hey everyone,

I'm rather new with datatables and have been searching for an answer to this issue. I've got a datatable in my angular project that is using server side processing to get/filter the data. On first call, the table is populated but still keeps the "No matching records found" at the bottom of the table.

When I filter results using an external dropdown and resend the parameters to the table and redraw it, the table is not populated even though I receive an answer with data inside. When I use the arrows for ordering the table or click on the pagination, the table is then populated.

There are some filters that are passed through the URL, so the issue isn't the data itself, but the rendering of the table. I receive all the results properly, I just can't seem to display them properly.

Here is the relevant code pieces:

export class AllLeadsComponent implements OnInit {



  //Datatables
  dtOptions: any = {};
  dtTrigger = new Subject();
  @ViewChild(DataTableDirective)
  dtElement: DataTableDirective;
}
  ngOnInit() {

      this.dtURL = this.hc.getUrl('customers/datatable', this.params);
      this.finalurl = `${this.envUrl.urlAddress}/${this.dtURL}`;

      this.dtOptions = {
        //retrieve: true,
        //ordering: true,
        //autoWidth: true,
        //destroy: true,
        paging: true,
        pagingType: 'full_numbers',
        pageLength: this.params.pageSize,
        serverSide: true,
        processing: true,
        dom: 'rtp',
        ajax: (dataTablesParameters: any, callback) => {
          this.http.post<DataTablesResponse>(this.finalurl, dataTablesParameters, {}).subscribe(resp => {
            this.customers = resp.data;
            this.total = resp.recordsTotal;
            callback({
              recordsTotal: resp.recordsTotal,
              recordsFiltered: resp.recordsFiltered,
              data: []
            });
          });
        },
        columns: [{ data: 'checkbox' }, { data: 'c.id' }, { data: 'c.name' }, { data: 'c.phone' }, { data: 'c.email' }, { data: 'c.source' }, { data: 'c.course' }, { data: 'i.institution' }, { data: 'c.time' }, { data: 'c.status' }, { data: 'u.name' }, { data: 'c.updated' }],
      }
    })
}

An example filter:

  onInstitutionChange() {
    this.params['filterByInst'] = 'inst_id';
    this.dtURL = this.hc.getUrl('customers/datatable', this.params);
    this.finalurl = `${this.envUrl.urlAddress}/${this.dtURL}`;
    this.rerender();
  }

The re-render:

  rerender(): void {
    try {
      this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
         dtInstance.ajax.reload();;
      });
    } catch (err) {
      console.log(err);
    }
  }

A sample result from my network:

A sample of the table showing as empty but has data. If I click on the pagination the table will then show the results:

Any help would be highly appreciated!

want to populate 2nd select box according to 1st select box value.

$
0
0

Example : country select based on city and state will be display.
i'm trying like following

function getStateList() {
var aStateList = new Array();
$.ajax({
url: '../../controllers/ajax.php?getstate=1',
type: 'POST',
dataType: 'json'
}).done(function(json){

        for (var a = 0; a < json.length; a++) {
            console.log(json[a][0]);
            console.log(json[a][1]);
            aStateList[a] = { 'label': json[a][0], 'value' : json[a][1] };
        }
        console.log(JSON.stringify(aStateList) );
        var final_arr = JSON.stringify(aStateList);
        return final_arr;
    }); 
}

var editor;

$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: '../../controllers/teacher_observation_LM.php',
table: '#example',
fields: [
{
label: 'Name of Teacher:',
name: 'teacher_observation_LM.teacher_id',
type: 'select'
},
{
label: 'Class:',
name: 'teacher_observation_LM.standard_id',
type: 'select'
}, {
label: 'Section:',
name: 'teacher_observation_LM.section_id',
type: 'select'
},{
label: 'Theme:',
name: 'teacher_observation_LM.theme',
type: 'select',
def: 'Y',
ipOpts: getStateList()
}]
} );

Ajax.php code :

if($_GET['getstate'] == 1)
{
$new[0][0] = 'a';
$new[0][1] = 'aa';
$new[1][0] = 'b';
$new[1][1] = 'bb';
echo json_encode($new);
}

Please help me

Print tab automatically close when autoPrint: true

$
0
0

Hello,
I am facing a problem with datatable print. I am working with a laravel project and when I press print button another tab open with my table data and then just before of preview the tab close automatically. It is happening only on chrome.

Print tab automatically close when autoPrint: true

$
0
0

Hello,
I am facing a problem with datatable print. I am working with a laravel project and when I press print button another tab open with my table data and then just before of preview the tab close automatically. It is happening only on chrome.

Change search box from keypress to enter key instead?

$
0
0

i want to change key events of search box of datatables to enter key bacause i want to avoid every character/letter user type it will not call api.

Datatable Server Side in Angular doesn't populate table properly

$
0
0

Hey everyone,

I'm rather new with datatables and have been searching for an answer to this issue. I've got a datatable in my angular project that is using server side processing to get/filter the data. On first call, the table is populated but still keeps the "No matching records found" at the bottom of the table.

When I filter results using an external dropdown and resend the parameters to the table and redraw it, the table is not populated even though I receive an answer with data inside. When I use the arrows for ordering the table or click on the pagination, the table is then populated.

There are some filters that are passed through the URL, so the issue isn't the data itself, but the rendering of the table. I receive all the results properly, I just can't seem to display them properly.

Here is the relevant code pieces:

export class AllLeadsComponent implements OnInit {



  //Datatables
  dtOptions: any = {};
  dtTrigger = new Subject();
  @ViewChild(DataTableDirective)
  dtElement: DataTableDirective;
}
  ngOnInit() {

      this.dtURL = this.hc.getUrl('customers/datatable', this.params);
      this.finalurl = `${this.envUrl.urlAddress}/${this.dtURL}`;

      this.dtOptions = {
        //retrieve: true,
        //ordering: true,
        //autoWidth: true,
        //destroy: true,
        paging: true,
        pagingType: 'full_numbers',
        pageLength: this.params.pageSize,
        serverSide: true,
        processing: true,
        dom: 'rtp',
        ajax: (dataTablesParameters: any, callback) => {
          this.http.post<DataTablesResponse>(this.finalurl, dataTablesParameters, {}).subscribe(resp => {
            this.customers = resp.data;
            this.total = resp.recordsTotal;
            callback({
              recordsTotal: resp.recordsTotal,
              recordsFiltered: resp.recordsFiltered,
              data: []
            });
          });
        },
        columns: [{ data: 'checkbox' }, { data: 'c.id' }, { data: 'c.name' }, { data: 'c.phone' }, { data: 'c.email' }, { data: 'c.source' }, { data: 'c.course' }, { data: 'i.institution' }, { data: 'c.time' }, { data: 'c.status' }, { data: 'u.name' }, { data: 'c.updated' }],
      }
    })
}

An example filter:

  onInstitutionChange() {
    this.params['filterByInst'] = 'inst_id';
    this.dtURL = this.hc.getUrl('customers/datatable', this.params);
    this.finalurl = `${this.envUrl.urlAddress}/${this.dtURL}`;
    this.rerender();
  }

The re-render:

  rerender(): void {
    try {
      this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
         dtInstance.ajax.reload();
      });
    } catch (err) {
      console.log(err);
    }
  }

A sample result from my network:

A sample of the table showing as empty but has data. If I click on the pagination the table will then show the results:

Any help would be highly appreciated!


DataTables with AngularJS 1.7

$
0
0

My project is using an older version of AngularJS in ASP.NET MVC, and I'm having some trouble using it with DataTables. The

<

table> tag is created like this:

<table ui-jq="dataTable" ui-options="dataTableOptions" id="search-results" class="display nowrap datatable cell-borders" style="width: 100%;">

Here's the code in my AngularJS controller:

`$scope.getMaterialHistory = function (model) {

    $http({
        method: 'POST',
        url: $scope.getUrl('/My/Method/Url'),
        data: { model: $scope.model }
    }).then(function successCallBack(response) {

        $scope.model.searchResults = response.data;

    }, function errorCallback(response) {
        alert("There was an error gathering theinformation. Please try again");
    });
};

$scope.dataTableOptions = {
    dom: "lfBrtip", 
    lengthMenu: [[25, 50, -1], [25, 50, "All"]],
    language: {
        emptyTable: 'No items matched your search criteria'
    },
    buttons: [
        {
            text: 'Export',
            className: 'button button:hover',
            extend: 'csv'
        }
    ]
};`

This works great... on the first "GET" operation. This part of the app is a search form with options that can be changed. If I change the options and click the submit button again, the search executes and I get more data, but my table is updated incorrectly. The length menu won't update with the new count of items in the table, and sometimes even shows I have zero results, when I have dozens of lines showing in the table. I can only think that it's not properly refreshing the data upon POST to the ASP.NET MVC controller method. I'm not sure how to fix this. Any suggestions?

How do I combine datetime field type with the mask plug-in?

$
0
0

When using datetime as an field type it would be good to check the input when the user types in date and/or time directly. Therefore I am looking for a combination of both field types, 'datatime' and 'mask' (Masked Inputs Plug-in) without writing my own custom field type plug-in.

{
    label: "Date:",
    name: "Date",
//  type: "mask",   does not make sense as it will be overwritten by the 'datetime' line 6
//  mask: "00.00.0000 00:00",
    type: 'datetime', 
    def:  function () { return new Date(); },
    format: 'DD.MM.YYYY HH:mm',
    opts: {
        showWeekNumber: true
    },
    attr: {
        maxlength: 16
    }
}

Get large quantity of data in module using jquery.datatables Server-side processing

$
0
0

Im trying to get jquery.datatables working using server side processing and pagination in a dotnetnuke module. Im using the documentation from the the followin article as a guide but i cant get it working.

I want to call the method from a control class but im getting an error:

_var viewmodel = new VesselModule.vesselListViewModel(moduleId, localizedSettings);
viewmodel.init();

    ko.applyBindings(viewmodel, $("#Vessels-" + moduleId)[0]);

    vm = viewmodel;

    // datatables

    function initDataTable() {
        //$.fn.dataTable.moment( 'MM D YY' );
        $("#VesselsTable-" + moduleId).DataTable({
            "paging": true,  
             "ordering": true,  
             "filter": true,  
             "destroy": true,  
             "orderMulti": false,  
             "serverSide": true,  
             "Processing": true,  
             "columnDefs": [  
                 { "width": "5%", "targets": [0] }  
             ],  
            "ajax":  
                {  
                    "url": vm.service.framework.getServiceRoot(vm.service.path) + "VesselInfo/GetListByPage/",  
                    "type": "POST",  
                    "dataType": "JSON"  
                },  
            "aoColumns": [
                {"mDataProp": "IMO"},  
                {"mDataProp": "VesselName"},  
                { "mDataProp": "ISNCompany" },
                {"mDataProp": "OwnerName"},  
                { "mDataProp": "VesselState" },
                {"mDataProp": "VesselName"},  
                { "mDataProp": "VesselType" },
                { "mDataProp": "InProgressDate" },
                { "mDataProp": "STDate" },
                {"mDataProp": "Actions"}
            ]  
        });

    }

_

The error im getting is:

(index):616 Uncaught SyntaxError: Unexpected token '}'

if i remove the code:

_ "aoColumns": [
{"mDataProp": "IMO"},
{"mDataProp": "VesselName"},
{ "mDataProp": "ISNCompany" },
{"mDataProp": "OwnerName"},
{ "mDataProp": "VesselState" },
{"mDataProp": "VesselName"},
{ "mDataProp": "VesselType" },
{ "mDataProp": "InProgressDate" },
{ "mDataProp": "STDate" },
{"mDataProp": "Actions"}
] _

The next error is returned:

_ jquery.js?cdv=800:8526 POST http://[dnn link page]/VesselInfo/GetListByPage/ 405 (Method Not Allowed)
send @ jquery.js?cdv=800:8526
ajax @ jquery.js?cdv=800:7978
ua @ jquery.dataTables.min.js:36
nb @ jquery.dataTables.min.js:37
O @ jquery.dataTables.min.js:29
T @ jquery.dataTables.min.js:31
ha @ jquery.dataTables.min.js:48
e @ jquery.dataTables.min.js:93
(anonymous) @ jquery.dataTables.min.js:93
each @ jquery.js?cdv=800:648
each @ jquery.js?cdv=800:270
m @ jquery.dataTables.min.js:82
h.fn.DataTable @ jquery.dataTables.min.js:167
initDataTable @ (index):598
(anonymous) @ (index):627
fire @ jquery.js?cdv=800:1037
fireWith @ jquery.js?cdv=800:1148
ready @ jquery.js?cdv=800:433
completed @ jquery.js?cdv=800:103_

if i add HttpPost in the method that is being called

  _  [HttpPost]
    public HttpResponseMessage GetListByPage()
    {
        try
        {

            return Request.CreateResponse("");
        }
        catch (System.Exception e)
        {
            // error
            log.Error(e.ToString());

            return Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError, e.Message);
        }
    }_

then the returned error is:

_ jquery.js?cdv=802:8526 POST http://[dnn link page]/VesselInfo/GetListByPage/ 401 (Unauthorized)_

Can you help? Thank you!

New Classic ASP Server-side script for DataTables 1.10.20

$
0
0

Hello Everyone,

I just wanted to share my Classic ASP server-side script that works with the current 1.10.20 DataTables - you may use it without major adjustments, except SQL query and connection data.
It fully supports pagination, ordering and searching through table.
Just make an ajax call for the file with below code and it will just work.

To generate Json I'm using below library:
http://www.webdevbros.net/2007/04/26/generate-json-from-asp-datatypes/
But you may change it if you wish.
IF you will not use this library, you will not need:

at the top of the file

<%@ EnableSessionState = false 
LANGUAGE="VBSCRIPT" CODEPAGE="65001"
%>
<%Option explicit%>
<!--#include file="./JSON.asp"-->
<%
'Initial variables - you may not need them:
Response.CodePage = 65001
Response.CharSet = "utf-8"
Response.AddHeader "X-XSS-Protection", "1"

'Declaration of all variables. If you don't want to declare everything - remove "Option explicit" above.
Dim  strFiltered, strEdit, strWhere, strSearch, strPaging, strOrder, StartRecord, PageNumber, RowsPerPage, draw, JsonAnswer, JsonHeader, rTotal, rFiltered, OrderCol, OrderDir, dbConn, rsReport, strReport, cmd, strCN

'So in simple way - you may start your file here by removing all above and putting <% here.

'Reading ordering data nd settin to empty if none. Empty should never happen, but it's just for safety.
OrderCol = Cint(Request("Order[0][column]"))
OrderDir =  Request("Order[0][dir]")
if not OrderCol = "" and not OrderDir = "" then 

'WHERE clause uses columns number, like e.g: ORDER BY 1 DESC, you may add translations to column names here, like e.g.: OrderCol = Replace(OrderCol,"0","Col1")
'We are adding 1 here, because DataTables indexes columns starting from 0
strOrder=" Order By " &OrderCol+1&" "&OrderDir 
else 
strOrder="" 
end if

'reading numbers sent by DataTables and setting them to defaults in case of empty (which should never happen):
draw = Cint(Request("draw"))

StartRecord = Cint(Request("start"))
if StartRecord = "" then StartRecord=0

RowsPerPage = Cint(Request("length"))
if RowsPerPage = "" then RowsPerPage=10

PageNumber = (StartRecord/RowsPerPage)

'reading search phrase - this one may be empty
strSearch = (Request("search[value]"))

'if not empty, then gerenate 'WHERE' Clause. Here you should edjust query to your DB.
if not strSearch ="" then
strWhere = " WHERE Col1 LIKE '%" & strSearch & "%' OR "
strWhere = strWhere & " Col2 LIKE '%" & strSearch & "%' OR "
strWhere = strWhere & " Col3 LIKE '%" & strSearch & "%' OR "
strWhere = strWhere & " Col4 LIKE '%" & strSearch & "%' OR "
strWhere = strWhere & " Col5 LIKE '%" & strSearch & "%'"
else
strWhere=""
end if

'generating pagination part of query:
strPaging = " OFFSET ("&PageNumber&")*("&RowsPerPage&") ROWS " &_
            "FETCH NEXT "&RowsPerPage&" ROWS ONLY"


'here is the most simple DB connection data and opening example - you should edit it as per your needs:
strCN = "Provider=MSOLEDBSQL;Data Source=.\SQL; Initial Catalog=shortcuts; Persist Security Info=False;User ID=ID; Password=Pass;"

Set dbConn = Server.CreateObject("ADODB.Connection")
Set rsReport = Server.createObject("ADODB.Recordset")
set cmd  = Server.CreateObject("ADODB.Command")

dbConn.mode = 3
dbConn.cursorlocation = adUseClient
rsReport.cursorlocation = adUseClient

dbConn.Open strCN
'connection is open here

'first query to count total number of records
strReport = "select COUNT(*) as Total from main"
rsReport.Open strReport, dbConn
'assigning value to variable
rTotal = rsReport("Total").value

'closing recordset and creating and executing new query
rsReport.Close
'first query to get data from DB to table with WHERE, ORDER and 'PAGINATION' clauses
strReport = "select * from main" & strWhere  & strOrder & strPaging
rsReport.Open strReport, dbConn

'Here is generated JSON from first query result. Using this library: http://www.webdevbros.net/2007/04/26/generate-json-from-asp-datatypes/
'You may here iterate through recordset and generate JSON manually.
JsonAnswer=(new JSON).toJSON("data", rsReport, false)

rsReport.Close
'second query to get number of results
strFiltered = "select Count(*) as Filtered from main" & strWhere 
rsReport.Open strFiltered, dbConn
'Assign number of results to variable:
rFiltered=rsReport("Filtered").value

'Closing and clearing connection - you may do it your way here:
set cmd.activeConnection = nothing
set cmd = nothing
dbConn.close
set dbConn=nothing
rsReport.close
set rsReport=nothing        

'finalizing JSON response - preparing header:
JsonHeader = "{ ""draw"": "& draw &", "& vbcrlf
JsonHeader = JsonHeader & """recordsTotal"": " & rTotal &", "& vbcrlf
JsonHeader = JsonHeader & """recordsFiltered"": " & rFiltered &", "& vbcrlf
 
'removing from generated JSON initial bracket { and concatenating all toghether.
JsonAnswer=right(JsonAnswer,Len(JsonAnswer)-1)
JsonAnswer = JsonHeader & JsonAnswer

'writing a response:
response.write(JsonAnswer)

%>

Setting header in AJAX request

$
0
0

I keep searching and hacking away at this, but can't figure out how to send headers to the AJAX request.

    ajax: {
        url: url,
        headers: {
            "Accept" : "application/ld+json",
            "Content-Type": "text/json; charset=utf-8"
        },
        beforeSend: function (request) {
            console.error(request);
            request.setRequestHeader("Accept", 'application/ld+json');
        },

The AJAX call is made to the URL, but the headers aren't correct, and beforeSend isn't called. (not show: dataFilter, which also doesn't seem to be called). The ajax object is passed on directly to jquery, right? The only exception is to not override the success call, which datatable uses internally, right?

Thanks,

Tac

Controlling itemsPerPage (length, pageLength) in AJAX request

$
0
0

I need to be able to control the itemsPerPage (aka the 'length' parameter) in the ajax request, and/or only have the 'start' parameter be on a page break. This is when using scroller.

        $('#example-table').DataTable({
            ajax: this.apiRequest({
                url: this.url
            }),
            columns: this.columns,
            serverSide: true,
            processing: true,
            scrollY: '400px',
            // displayLength: 17, // not sure how to adjust the 'length' sent to the server
            // pageLength: 14,
            dom: 'ift',
            scroller: {}

Is there any way to do this? I can't figure out why datatables chooses the values it does anyway, I'm monitoring the request (by setting ajax to a function), and the records per page (length) it requests seem to be calculated internally (since they're different for each table).

I've played around with displayLength and pageLength, but they don't seem have an much of an effect. In particular, pageLength seems to be ignored with an AJAX call, but that'd be the most natural place to set it. However, it wouldn't be enough, because the start value changes while scrolling, but not to a full new page.

That is, if my server returns 30 items per page, and I only have control of the page number (not the starting element), then I don't want a datatable request of start=15, length=30, since I have to convert this to a page. I know I can implement a pipeline and make multiple requests, but this seems like a lot of work, when really I just want control over the page length. (and ideally the start parameter).

Is there an option to see the ajax length parameter?

Thanks.

Custom/Reactive Column Editor

$
0
0

In regards to the Editor, is there a way to make something reactive to what was selected in another column?

For example, I have two columns -- the first is a selector of "type" and the second column is the "value."

I want to make it so that a few of the type's (First column) have masked text editors on the value (Second column) field. I'd like for a few of the type's to also have a "dropdown" selector for the value field as well.

i.e.

if User selects Type A, B, or C on Column 1
Column 2 displays a TextBox with masked input.

if User selects Type D or E on Column 1
Column 2 displays a selector (with constant values)

Is that possible?

I should add that this is an "inline" editor -- it looks like there is something of this in Dependent fields example. The data specified, though, in column 2 would be relevant on the server-side for either masked input or a constant.

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


Individual column searching (text inputs) does not show input text after page changing

$
0
0

Hello,

I’m using the “Individual column searching (text inputs)” explained in

https://datatables.net/examples/api/multi_filter.html

but I have a problem.

When I change page and later come back, the values written inside the input controls are not displayed. The filters work (i.e. the columns contain only the filtered results), but the searched words are not visibile. The global Search is instead populated.

In DataTable constructor I set:

  `stateDuration: -1, //-1 means session storage
  `stateSave: true, 

and

    `initComplete: function () {
    `var r = $('#myTableId tfoot tr');
      `r.find('th').each(function(){
        `$(this).css('padding', 8);
      `});
      `$('#myTableId thead').append(r);
      `$('#search_0').css('text-align', 'center');

      `var api = this.api();

      `// Apply the search
      `api.columns().every(function() {
        `var that = this;       
        `$('input', this.footer()).on('keyup change', function() {
          `if (that.search() !== this.value) {
            `that.search(this.value).draw();
          `}
            `});
        `});
     `},

Could anyone help me figure out where I'm wrong?

Thanks in advance, Leonardo

datatables checkbox not showing in modal popup bootstrap 4

$
0
0

I'm creating a table and applying DataTable all dynamically showing the table in a modal window using Nakupanda DialogMessage (same issue happen with regular bootstrap modal window). Now my only issue is that checkboxes are not being displayed in the modal window, if I show the table not in the modal window it shows perfectly. I was checking and in the modal window, class dt-checkboxes-cell is missing as well as the input type checkbox not sure why.

Below is my sample code:

$('#showinmodal').click(function() {
    // --- BootstrapDialog Message ---
    var queryMsg = $("<div/>");
    
    var tableQueries = $("<table/>", {
        "id": "t_queries",
        "class": "display",
        "style": "width:100%"
    });
    
    tableQueries.append("<thead><tr><th></th><th>Name</th><th>Lastname</th></tr></thead><tbody><tr><td>1</td><td>A1</td><td>B1</td></tr><tr><td>2</td><td>A2</td><td>B2</td></tr><tr><td>3</td><td>A3</td><td>B3</td></tr></tbody>");
    tableQueries.appendTo(queryMsg);
    // --- End BootstrapDialog Message ---  

    tableQueries.DataTable({
        "order": [],
        "columnDefs": [                     
            {
                "targets": 0,
                "checkboxes": {
                    "selectRow": true
                }                               
            }                        
        ],
        "select": {
            "style": "multi"
        },
        "order": [[1, 'asc']],                      
        "paging": true,
        "fnInitComplete": function() {
            showDialog(queryMsg);
        }
    });         
    
    function showDialog(queryMsg) {
        BootstrapDialog.show({
            title: "Title",
            message: queryMsg,
            size: BootstrapDialog.SIZE_WIDE,
            closable: false,
            buttons: [{
                label: "Submit",
                cssClass: 'btn-primary',
                action: function(dialogRef) {
                    dialogRef.close();                              
                }
            }, {
                label: "Close",
                action: function(dialogRef) {
                    dialogRef.close();
                }
            }]
        });
    }
});

Scroll page when reordering row

$
0
0

I've noticed that the old datatable scrolls the page (body or html!) when you was reordering the row and you was at the bottom of the page. The new one however does not and you need to scroll manually. Is there an option to activate scrolling the page when dragging?

NOTE: I know it works when you have scrollY active but I dont want the table to have an overflow-scroll

Trigger mouse click on mousedown

$
0
0

I'm attempting to initiate a drag by clicking mousedown. Is it possible to select the row on which mousedown occurs by triggering a click?

serverside update data

$
0
0

Hi, how can I use ajax.reload() in datetimepick callback functions??

let method = '';
let url = '/myAjaxFunc/';
method = 'POST';
$.ajax({
url: url,
method: method,
data: { "selectDate": moment(e.date).format("YYYY-MM-DD HH:mm"),
"start":0,
"length":10,
"draw":0,
}
}).success(function (data, textStatus, jqXHR) {

console.log(data['data']);
//$('#tb12').DataTable({ajax:data['data']}).ajax.reload();
$('#tb12').DataTable().destroy();

if ( $.fn.dataTable.isDataTable( '#tb12' ) ) {
    console.log('111111111111111');
    table = $('#tb12').DataTable({"ajax":data['data']}).ajax.reload();

}
else {
    console.log('2222222');
    table = $('#tb12').DataTable({"ajax":data}).ajax.reload();

}

})

it will show error, can't init datatable twice....

Viewing all 81347 articles
Browse latest View live


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