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

Responsive + Editor with opt-in for inline editable fields

$
0
0

I'm using a setup similar to this, but instead of using this

$('#example').on( 'click', 'tbody td:not(.child)', function (e) {
    editor.inline( this );
} );

I'm doing this

$('#example').on( 'click', 'tbody td.editable', function (e) {
    editor.inline( this );
} );

which makes it a more "opt-in" method than just assuming the user can edit all the fields. This has worked great until I realized that same method isn't carrying over to the "DTR" child elements (the elements that get pushed off the page when the viewport isn't large enough to show them - see screenshot below). I'm hoping to find a way to carry my className: 'editable' classes set in the columns option over to the child elements as well. Any help would be much appreciated!

DTP child elements


How can I reload data in datatable after doing any CRUD operation?

$
0
0

Hi,
I am developing an eletron app that uses a sqlite database. I use a query to fetch data and populate table data using its results. Whenever I do a CRUD operation I initialize table but despite change in database, no change in table data is occurred.
I use below code to populate table:

window.getData = function() {
  var db = require('./database/database');

  const results = db.prepare('SELECT name, family, mobile FROM customer').all();

  var html = '';

  for (const row of results) {
    html += '<tr>';
    html += '<td>';
    html += row.name;
    html += '</td>';
    html += '<td>';
    html += row.family;
    html += '</td>';
    html += '<td>';
    html += row.mobile;
    html += '</td>';
    html += '</tr>';
  }

  console.log(results);

  document.querySelector('#table_id > tbody').innerHTML = html;
};

and following to configure datatable:

$('#table_id').DataTable({
      retrieve: true
    });

Is there any way to reload data in datatable for my case?

Thanks in advance

como puedo utilizar el buscador de mi navbar y no el de datatable para filtrar registros de mi tabla

$
0
0

Tengo en mi navbar un buscador con diseño personalizado, lo que me gustaría es poder utilizarlo y esconder el que trae datatable por defecto, algun ejemplo lo agradeceria.

FixedHeader too wide when fixed

$
0
0

Hello,

I have the FixedHeader working here http://clb0212.wpengine.com/publications/ on a public test site.

When I scroll down, it is a correct fixed header, but the header size is twice as wide as it should be. What am I doing wrong?

thanks!
Christina Black

why the $1 and $10 is the same value when executed?

$
0
0

$this->datatables->add_column('view',
'<a href="javascript:void(0);" class="edit_record btn btn-info btn-xs" data-kode=$1 data-nama=$10

Handle editors upload field exceptions

$
0
0

Hey,

I'm using ajax object configuration for upload type of input. Everything works great, I just have an issue where if validation of uploaded image is rejected, server returns status code 422, so datatables displays "A server error occurred while uploading the file".

For other ajax requests I was able to handle this inside "error" function, but in this case it doesn't seem to be fired. Bellow is my code:

{
    label: 'Image:',
    name: IMAGE_NAME,
    ajax: {
        url: route('dt.post'),
        type: 'POST',
        data: (data) => {
            data._token = window.Laravel.csrfToken;
        },
        dataFilter: function (response) {
            const json = JSON.parse(response);
            $.each(json.files, function ( table, files ) {
                $.fn.dataTable.Editor.files[table] = files;
            });
            return response;
        },
        error: function (xhr, e/*, thrown*/) {
            let data = xhr.responseJSON;
            if (data && data.hasOwnProperty('fieldErrors')){
//                success(data);
            } else {
//                error(xhr, e, thrown);
            }
        }
    },
    type: 'upload',
    display: function ( file_id ) {
        ...
    },
    clearText: "Clear",
    noImageText: '-'
}

Any idea why error function is not fired when server code != 200?

Beside this approach I also tried to use ajax function instead of object function(method, url, data, success, error) (I use this as default method all over the project) so that I was able to call success or error callback, depending on what happened. If I add this to my upload field, upload field will completely ignore function and just make a POST request to the same page user is currently on. This works for DataTables data calls though, so not sure why it doesn't here...

Is there a way to handle validation errors and prevent "A server error occurred while uploading the file" getting displayed for upload field?

P.S.: After using DataTables for 5+ years I think, I think I could easily say it's one of the most advanced and flexible packages I ever used. GJ Allan and team :)

Grid Click event doesn't works after reload

$
0
0

Hello,

I have DataTable with external button (Search) to Filter Data, It works Fine with First Time Load / Page Load (refer 1 Time Click.PNG)

I need to Filter Table with multiple criteria so added a search button on the same page and Called reload Fuction

I search click it re-loads Data correctly but Grid click event doesn't works after search button click

how to resolve this?

Please suggest ,

Thanks

**ASP.NET PAGE **

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<style type="text/css">

</style>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel ID="UpdatePanelSalesOrder" runat="server">
<ContentTemplate>
<div class="row no-gutters">
<div class="col-sm-3">
<select class="custom-select custom-select-sm" runat="server" id="txtCategory">
</select>
</div>
<div class="col-sm-3">
<asp:Button ID="btnSearch" runat="server" Text="Search" CausesValidation="False"
CssClass="btn btn-secondary btn-sm btn-block" OnClick="btnSearch_Click" />
</div>
<div class="col-sm-6">
</div>
</div>
<table id="tblOrder" class="table-striped table-bordered table-hover table-sm" style="width: 100%">
<thead>
<tr style="height: 35px">
<th>Ord.No</th>
<th>Date</th>
<th>Product Name</th>
</tr>
</thead>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="theScript" runat="server">
<script type="text/javascript">

    $(document).ready(function () {
        fill_table();
        $('table tbody').on('click', 'tr', function () {
            alert("Data Table clicked");
        });
    });

    function fill_table()
    {
        var table = $('#tblOrder').DataTable(
        {
            'bPaginate': true,
            'bLengthChange': false,
            'bFilter': false,
            'bInfo': true,
            'bAutoWidth': false,
            'responsive': false,
            "scrollX": true,
            'ajax': {
                url: "SalesOrderIssue.aspx/get_PendingOrder",
                method: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                dataSrc: function (data) {
                    return $.parseJSON(data.d)
                }
            },
            'columns': [
                { data: "ORDER_NO" },
                { data: "ORDER_DATE", type: "date", render: function (data) { return moment(data).format("MM/DD/YYYY"); } },
                { data: "ProductMaster.PRODUCT_NAME" },
                { data: "SizeMaster.SIZE_NAME" },
            ],
            'order': [[1, 'asc']],
            'error': function (xhr, status, error) {
                alert('Error Occured -' + error);
            }
        })
    }

  ``` function reload_data() {
        fill_table();```
    }
</script>

</asp:Content>

Code Behind

[WebMethod]
public static string get_PendingOrder()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string strOrderList = serializer.Serialize(_listOrderMasterDTO);
return strOrderList;
}

    private void fill_PendingOrder()
    {
        try
        {
            var ActiveDate = DateTime.Now;
            var startOfMonth = new DateTime(ActiveDate.Year, ActiveDate.Month, 1);

            DateTime dtFromDate = Functions.ConvertToDateTime(m_strStartDate);
            DateTime dtToDate = Functions.ConvertToDateTime(m_strEndDate);
            _listOrderMasterDTO = new OrderMasterService().GetOrderMasterByDateAndSubCatIdList(dtFromDate, dtToDate, "", 0, Convert.ToString(txtCategory.Items[txtCategory.SelectedIndex].Text), Convert.ToString(Session["g_DBNAME"]));
        }
        catch (Exception ex)
        {
            Module.ShowError(ex, this, this.Page.GetType());
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            fill_PendingOrder();
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("$(function(){");
            sb.Append("reload_data();");
            sb.Append("});");
            ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "", sb.ToString(), true);
        }
        catch (Exception ex)
        {
            Module.ShowError(ex, this, this.Page.GetType());
        }
    }

Clicking on column toggles boolean value

$
0
0

Hello

I have a table currently with 5 columns one of which is a boolean value,
I was trying to implement a solution where the user clicks on the column
and that row column 5 would toggle from True to False or False to True

I could find a way to get the data but not update or set the data and have the table refresh with the correct data
eg.

var data = table.row('.selected').data();
alert(data[5]);

I found that if i set the data value manually with say table.row('.selected').data()[0][5] = "False"
then run table.draw() it does not update

What's the best way to do this?

Thanks


Editor not invoked in child table

$
0
0

Hi everyone..

Given below is the link to my page where I have used parent-child system.
https://e-reporting.in/Data/HTC_Bill/index1.php

When I expand the first column i.e. Bill **of any row, the child table gets populated and new row could be added using Add Bill button. But when click on subsequent rows to expand them, the **Add Bill Button doesn't work as an **empty editor **without any fields do appear.

Please see and help me to get rid of the above.

Thanks & Regards
Shatrughan Sangwan

DataTables Scroll question.

$
0
0

Is it possible to use the ScrollY effect but set the height depending on how many rows you want to be shown like in pagination?

FooterCallback on btn Click

$
0
0

Hello,

I am trying to create an attendance register for a local Club that lists attendee's, displays if Members or not, and populate Subs column with appropriate session payment and show total Subs £ for session.

I am using Bootstrap Toggle Button to trigger the events, including storing attendees to MySQL.

As you can see from the second image, it's all working fine apart from the total in the footer. I am trying to use the FotterCallback function to sum up the Subs column,

       ```$(document).ready(function(e){
            $('#tblRiders').DataTable({

                "footerCallback": function ( row, data, start, end, display ) {
                    var api = this.api(), data;

                    // Remove the formatting to get integer data for summation
                    var intVal = function ( i ) {
                        return typeof i === 'string' ?
                            i.replace(/[\$,]/g, '')*1 :
                            typeof i === 'number' ?
                                i : 0;
                    };

                    // Total over all pages
                    total = api
                        .column( 6 )
                        .data()
                        .reduce( function (a, b) {
                            return intVal(a) + intVal(b);
                        } );

                    // Total over this page
                    pageTotal = api
                        .column( 6, { page: 'current'} )
                        .data()
                        .reduce( function (a, b) {
                            return intVal(a) + intVal(b);
                        }, 0 );

                    // Update footer
                    $( api.column( 6 ).footer() ).html(
                        ('£' + total)
                    );
                },```

But this is obviously a static function that triggers on page load, which is not what I am aiming for. I have also tried

$('#example').DataTable().ajax.reload();

in the

$(document).on('change', '.toggleBtn', function(ev)

I have also tried o use the FooterCallback function inside the toggleBtn function, but I can't get it to work.

Any ideas?

Thanks in advance.

Add button to each row in Server-Side-Datatable

$
0
0

I have a PHP program with a datatable, which works fine. Each row has a button (“Manage”) for CRUD actions which, when clicked, opens up a Bootstrap 4 modal :

I changed the program to Datatables-Server-Side because the DB table has thousands of rows. This too works fine, but I cannot add the “Mange” button to the datatable rows.

My HTML :

<html>
<head>
    <title>TEST (DataTables)</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.bootstrap4.min.css">
    <link rel="stylesheet" type="text/css" href="style.css">    
</head>
<body>
    <div class="container-fluid">
        <div class="jumbotron jumbotron-fluid mr-n2 ml-n2 mb-n2 rounded bg-secondary">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12 col-lg-offset-2 myMargTop20 bg-white rounded">
                        <table id="example" class="display table table-bordered table-hover dt-responsive nowrap rounded bg-info" cellspacing="0" width="100%">
                            <br>
                            <thead>
                                <tr>
                                    <th>Id</th>
                                    <th>Full Name</th>
                                    <th>User</th>
                                    <th>Phone</th>
                                    <th>Create Date</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#example').dataTable({
                'scrollX': true,
                'pagingType': 'numbers',
                'processing': true,
                'serverSide': true,
                'ajax': 'datatablesServerSide.php'
            });
        });
    </script>
</body>
</html>

My datatablesServerSide.php :

<?php
$table = "users";
$primaryKey = "usrId";
$columns = array(
  array("db" => "usrId", "dt" => 0),
  array("db" => "usrFullName", "dt" => 1),
  array("db" => "usrName", "dt" => 2),
  array("db" => "usrPhone", "dt" => 3),
  array("db" => "usrCreateDate","dt" => 4, "formatter" => function($d, $row) {return date("d-m-Y", strtotime($d));})
);
$sql_details = array(
  "user" => "root",
  "pass" => "",
  "db"   => "a_my_project",
  "host" => "localhost"
);
require( "ssp_with_UTF8.class.php" );
echo json_encode(
  SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);

I would appreciate any hint to start me going. I read numerous entries here and elsewhere but none helped...
Thank you!

Filter Operations on Server

$
0
0

Hi dears I have a problems with filter it can't filter operation like

{
                        "mRender": function(data, type, row) {
                            return parseInt(row.salesprice / row.number - row.buyingprice / row.number);
                        }
and 
    {
                        "mRender": function(data, type, row) {
                            return parseInt(row.number - row.sum);
                        }
plss help me 
 **it is my filter code **

fixedHeader: true,
            pageLength: -1,
            initComplete: function () {
                this.api().columns().every( function () {
                    var column = this;
                    var select = $('<select style="width:100%"><option value=""></option></select>')
                        .appendTo( $(column.header()))
            .on( 'click', function (e) {
                e.stopPropagation();
            })
                        .on( 'change', function () {
                            var val = $.fn.dataTable.util.escapeRegex(
                                $(this).val()
                            );

                            column
                                .search( val ? '^'+val+'$' : '', true, false )
                                .draw();
                        } );

                    column.data().unique().sort().each( function ( d, j ) {
                        select.append( '<option value="'+d+'">'+d+'</option>' )
                    } );
                } );
            },

it is the result

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

Column Render not rendering properly.

$
0
0

Hi All,

Request your help, when I manually execute the php program the output is as below(PHP Output), the "Output" column is an array , so in my ajax i have the below lines(AJAX Query), it is rendering the first array (0) properly , but the second array(1) the value is display as single line "FAILED FAILED FAILED" rather than multiple lines as 

FAILED
FAILED
FAILED

PHP Output

    [0] => Array
        (
            [Server] => T1
            [Task] => T01
            [Output] => Array
                (
                    [0] => FAILED
                )

        )

    [1] => Array
        (
            [Server] => T2
            [Task] => T01
            [Output] => Array
                (
                    [0] => FAILED 
                    [1] => FAILED
                    [2] => FAILED
                )

        )

AJAX Query

            columns: [
                        { data: "Server" },
                        { data: "Task", className: "dt-body-left h8" },
                        { data: "Output",
                          render: function (data, type, row) {
                                           var odata = '';
                                           for (i=0; i<data.length; i++) {
                                                odata += '<p class="dt-body-left h8 text-danger" colspan="2">' + data[i] + '</p>'
                                           }
                                           return odata;
                                  }
                        }
            ]

Help with SSP Class multiple table query

$
0
0

Hello,
I am very new to datatables and I need help with a query to work with ssp.class.php

What would be the equivalent of

“SELECT tableA.*, tableB.*, tableC.offer_id, tableC.main_id, tableC.stat, tableD.data FROM tableA, tableB, tableC, tableD WHERE tableA.main_id = tableD.main_id AND tableC.main_id=tableA.main_id AND tableA.rep_id=tableB.rep_id AND tableC.offer_id IN (SELECT MAX(offer_id) FROM tableC GROUP BY main_id) GROUP BY tableA.main_id ORDER BY tableA.main_id DESC”;

?

It’s just multiple table SELECT query with multiple WHERE clause, but I am unable to make it work with ssp class.

Highly appreciate your help

JP


Get usage count of foreign key

$
0
0

Hi,

I have this file called table.ref.php that sets up the editor for my list of references (as in journal articles) in table 'ref' like so:

// Alias Editor classes so they are easy to use
use
    DataTables\Editor,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Mjoin,
    DataTables\Editor\Options,
    DataTables\Editor\Upload,
    DataTables\Editor\Validate,
    DataTables\Editor\ValidateOptions;

// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'ref', 'id' )
    ->fields(
        Field::inst( 'id' ),
        Field::inst( 'author' ),
        Field::inst( 'year' ),
        Field::inst( 'title' ),
        Field::inst( 'journal' ),
        Field::inst( 'etcetera' ),
        Field::inst( 'count' )->getValue( 9 ),
        Field::inst( 'user' )
    )
    ->where( 'user', $_SESSION['user'] )
    ->process( $_POST )
    ->json();

Now for the field 'count' I would like to return the number of times each reference is used in another table called 'cases'. Each case only ever has one reference, but one reference can be used for multiple cases. Is there an easy way to replace the number 9 in above code snippet with the actual number of cases that the reference is cited for?

Creating a Datatables from a json files -> blank page

$
0
0

Hi,

I'm trying to create a DataTables. For that I have a data.json file that looks like :

[
  {
    "Chariot": "ASSET57",
    "Zone": "STOC2",
    "Type": "armoire",
    "Quantité": 5,
    "sav": "non"
  },
  {
    "Chariot": "ASSET130",
    "Zone": "ARRI1",
    "Type": "armoire",
    "Quantité": 0,
    "sav": "oui"
  },
  {
    "Chariot": "ASSET44",
    "Zone": "DEPA1",
    "Type": "chaise",
    "Quantité": 0,
    "sav": "non"
  }
]

Then a tableau.js where I write :

$(document).ready(function() {
    $('#example').DataTable( {
        data: data,
        columns: [
            { data: "Chariot" },
            { data: "Zone" },
            { data: "Type" },
            { data: "Quantité" },
            { data: "sav" },
        ]
    } );
} );

Both data.json and tableau.js are in a /data repository
and finally the html file where I put :

<head>

<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
  
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>

</head>

<body>

<script type="text/javascript" src="data/tableau.js"></script>

</body>

And I obtain a blank page... I don't understand what's wrong.

Could you help me ?

Thank's in advance !

DataTables Not Fully Working Correctly with ASP.NET GridView Paging (only searches current page)

$
0
0

I have an ASP.NET GridView with the following setup:
1. Sorting is implemented using ASP.NET GridView's Sorting (OnSorting="gridList_Sorting")
2. Paging is implemented using ASP.NET GridView's Paging (OnPageIndexChanging="gridList_PageIndexChanging")
3. Searching/Filtering is implemented using JQuery DataTables

Background: The setup is that way because the GridView needs to be editable. I tried implementing sorting, paging, and searching/filtering exclusively using DataTables but I get the issue of the row-being-edited jumping unpredictably within the GridView (the row's position changes when it's clicked to be edited), and I wasn't able to solve it.

Going back, the issue is DataTables is only able to filter if the record occurs in the current GridView page. Example: In the edited image below, searching for "Fiona Green" will not display the filtered results. However, searching for "Hope" will display the filtered results.

Due to a tight time constraint, I need to maintain the setup (sorting and paging is done by ASP.NET GridView while searching/filtering is done by JQuery DataTables). I hope someone can help advise on troubleshooting and solving this issue. Advanced thanks!!!

Render Jumpy / table glitchy.

$
0
0

My first datatable. Works ok, but....

I have a datatable populated by a php generated html table so the data is in the DOM for SEO. It builds out the table then jumps down to size, so there is quick noticeable glitch. 400 rows.

Is there a best practice for a smoother render?
I am not strong on front end.

thanks for any ideas.

Column width not working

$
0
0

Hi I have read the other posts in the forum. Did not find solution.

<--!  Datatables spezific files:-->
    <link href="~/datatables/dataTables.bootstrap.min.css" rel="stylesheet" />
    <script src="~/datatables/jquery.dataTables.min.js"></script>
    <script src="~/datatables/dataTables.bootstrap.min.js"></script>*

<div id="datatablestest" style="width: 460px;margin: 0 auto;">
    <table id="datatableresult" class="table table-condensed table-striped table-bordered  table-hover" cellspacing="0">       
    </table>
</div>
var daTable = $('#datatableresult').DataTable({
    "ajax": {
        "url": daUrl,
        "dataSrc": ''
    },
    "autoWidth" : false,
    "columns": [
        { data: "JourID", title: "JourID", width: '50px'},
        { data: "JourTime", title: "JourTime", width: '50px'},
        { data: "Zust1", title: "Zust1", width: '30px'},
        { data: "Dokname", title: "Dokname", width: '100px'},
        { data: "Doktype", title: "Doktype", width: '100px'},
        { data: "JourInhaltTextOnly", title: "JourInhaltTextOnly", width:'550px'},

    ],
    "paging": false,
    "scrollY": 400,
    "scrollX": true,
});

Has no effect at all.
DataTables makes column width that have nothing to do with the set options.
Am I misunderstanding completely, how this works ?
Thanks for Info
Cheers, Michael

Viewing all 81693 articles
Browse latest View live