Quantcast
Channel: Free community support — DataTables forums
Viewing all 35272 articles
Browse latest View live

Behavior question: Display all rows then shrink to 10 rows

$
0
0

Hi,

I'm using a loop to generate HTML code. I have found the table display all rows first then reformat itself to the default number of rows (10). Is this normal behavior? Is there any trick to avoid display all rows first? I understand that using ajax call can achieve that. However, dynamic HTML generation might be easier for me to manipulate HTML code.

The following is sample code to generate HTML code (ASP.Net MVC):

@foreach (var v in Model)
{
<tr>
<td>
@Html.DisplayFor(x => v.Column1)
</td>
<td>
@Html.DisplayFor(x => v.Column2)
</td>
</tr>
}

Thanks.

jb48888


Editor: type select displays it's value after change

$
0
0

Hi,

I am having trouble with inline editing for type="select", could you please check following link?

http://live.datatables.net/zuwodula/8/edit

*type of second column is "select", but when I change it, display value is changed to id,
it should display options label,

how can I achieve this?

one thing I can do is: track change event of select and manipulate dom, which I don't want.

Clearing State on Page Reload

$
0
0

I would like to clear the state of a table on page reload. I use a lot of ajax for filtering and reloading the table.

I think the answer is to delete the cookie, but I am unable to find documentation that works.

Server Side Limit of -1 throws ajax error

$
0
0

Hi, when I choose the all option in the show entries box it throws a json error because the -1 is not an option in mysql. I have gotten around it by detecting if it is a -1 and then adding the limit only if it's not equal to -1 but I wondered if there was a better way.

Thanks!

How do I redraw a table using an already-built array?

$
0
0

I need to redraw my datatable using an array function I've already built. I am manipulating the demo datatable content for the dt_basic datatable.

What it does naturally: When a user types a search term in the search filter, the search filter removes any rows that do not match the search variable and only shows rows which match it.

What I need it to do: I need it to pull the relevant rows to the top of the table and continue to display all the other rows beneath.

To this end, I have written an array function shown below.

My question: How do I now tell the table to redraw using my array variable rather than just console logging it?

Special note about the function: One of my columns has a select dropdown status field, but all the others are just regular alpha-numeric cells. I've written in logic to ask the search to ignore the dropdown options.

$('#dt_basic_filter input[type="search"]').on("keyup change", function () {
                var returnArray = [];
                var value = $(this).val();
                var dTable = $('#dt_basic').dataTable();
                var tableData = dTable.fnGetData();
                var wasFound = false;
                $.each(tableData, function (key, row) {
                    wasFound = false;
                    $.each(row, function (k, v) {
                        if ($($.parseHTML(v)).find(".selected-status").length > 0) {
                            //if there is a selected status and the value is the search term, log it.  
                            //doesn't include dropdown values
                            var statusText = $($.parseHTML(v)).find(".selected-status").text();
                            if (statusText.toLowerCase().indexOf(value.toLowerCase()) > -1) {
                                returnArray.splice(0, 0, row);
                                wasFound = true;
                                return;
                            }
                        } else {
                            //not in a column with drop down and we match the search term
                            if ((v).toLowerCase().indexOf(value.toLowerCase()) > -1) {
                                returnArray.splice(0, 0, row);
                                wasFound = true;
                                return;
                            }
                        }
                    });
                    if (!wasFound) {
                        returnArray.push(row);
                    }
                });

                console.log(returnArray);
            });

Editor - Chained select boxes and multiple query inserts on update.

$
0
0

Hi. I wasn't able to find this in the documentation, or I might have searched for the wrong wording and such.

I will like to know if the following scenarios are possible at all if not, where should I start adding my own functions to make it all work.

1) Chaining Select boxes and validation.

On client side I have the following fields:

                        {label: "Subcontracted",
            name:"subcontracted.to_c",
            type:"select"},
            {label:"Operative",
            name:"jobs_assigned.id",
            type:"select"}

I need to enable the one only if the other is set to null, so for example the field labeled Operatives should be active and validated only if the field labeled Subcontracted is set to an empty value. However if the field Subcontracted is set to anything but an empty value than, the field Operatives must be set to an empty value. I can write my own javascript function to get around this, that's the easy part, however rule of thumb, never trust the user data, so I need to validate this on the server side.
Currently I have both of the fields set to use: ->validator( 'Validate::dbValues' ) but this fails when the submitted value is empty. So the question here is, I guess I need to create my own validation function, which will match agains db values + empty right?

2) If all validation have passed, before updating the tables (multiple joined tables) which is nicely handled by editor, I need to run some additional queries. I need to do some loop's and modification in other tables which are not included in the join at all, and some operations which requires me to loop the same query a few times, where should I include this? Also how should I handle it if the user edits multiple rows? Is the validation done for all of the rows then it moves on to executing the query or is it done for each row seperately in a loop function?

This is how my server-side script looks at the moment:

$editor=Editor::inst( $db, 'jobs' )
    ->fields(
        Field::inst( 'company.Name' ),
        Field::inst( 'stores.short_add' )->validator( 'Validate::notEmpty' ),
        Field::inst( 'jobs.description' )->options( 'job_descriptions', 'id', 'short_description', function ($q) {
                                    global $owner;
                                    $q->where('owner',$owner);})
                                    ->validator( 'Validate::dbValues' ),
        Field::inst( 'job_descriptions.short_description' ),
        Field::inst( 'jobs.startdate' ),
        Field::inst( 'clients.Company_Name' ),
        Field::inst( 'operatives.name' ),
        Field::inst( 'jobs.freq' )->validator( 'Validate::numeric' ),
        Field::inst( 'jobs.freq_type' )->validator( 'Validate::numeric' )->options( function () {
        return array(
            array( 'value' => '0', 'label' => 'Interval' ),
            array( 'value' => '1', 'label' => 'Set Date' )
        );
    } ),
        // Field::inst( 'subcontracted.to_c' )->options( 'clients', 'id', 'Company_Name')->validator( 'Validate::dbValues' ),
        Field::inst( 'subcontracted.to_c' )->options( function () use ( $db ) {
             $out[] = array('value' => '', 'label' => 'Select from list');
            $attrList=$db->selectDistinct ('clients',['id','company_Name']);
            while ( $row = $attrList->fetch() ) 
                {
                $out[] = array(
                        "value" => $row['id'],
                        "label" => $row['company_Name']
                );}     
            return $out;
            })->validator( 'Validate::dbValues' ),
        Field::inst( 'jobs_assigned.id' )->options( 'operatives', 'id', 'name', function ($q) {
                                    global $owner;
                                    $q->where('owner',$owner);})
                                    ->validator( 'Validate::dbValues' ),
        Field::inst( 'jobs.owner' )->setValue($owner)
    )
    ->leftJoin( 'stores', 'stores.id', '=', 'jobs.store_id' )
    ->leftJoin( 'company', 'stores.company_id','=','company.id')
    ->leftJoin( 'subcontracted', 'subcontracted.jobid','=','jobs.id')
    ->leftJoin( 'clients','clients.id','=','subcontracted.to_c')
    ->leftJoin( 'jobs_assigned','jobs_assigned.jobid','=','jobs.id')
    ->leftJoin( 'operatives','jobs_assigned.operativeid','=','operatives.id')
    ->leftJoin( 'job_descriptions','job_descriptions.id','=','jobs.description');
    $editor->where('jobs.owner',$owner);

    $editor->process( $_POST );
    $editor->json();

Hope my questions aren't too much all over the place....

RowReorder extension is preventing events reaching Select extension for first column

$
0
0

When I have a table with the Select and RowReorder extensions enabled and the Select extension is setup to only listen for clicks on the first column the Select extension never receives mouse events.

An example is here: https://jsbin.com/biziqo/19/edit?js,output

You cannot select a row using the first column. But if you comment out the RowReorder extension it works fine.

Would it be possible for the RowReorder extension to allow events to bubble? Or is there more to it than that?

Model only has the visible items

$
0
0

Hi everyone,

I'm fairly new in using this dataTable plugin... What I want to do is use this plug in for its pagination function... and when I click a button have all the items, including items not in the current page, to be saved in my database... My problem is, the Model only contains the items in the current page... Is there a way to get all the items in the table?

Thanks,
Ian


Firefox specific issue: Datatable unecessary Child Row issue when bootstrapped and responsive

$
0
0

I am using datatables for a long time. However, I have encountered styling issues in the latest version. The html header details specific to datatables are as below:

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.2.0/css/select.bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.0/css/responsive.dataTables.css"/>




OS: Ubuntu 16.04 LTS

The application works fine in Chrome Version 52.0.2743.116 (64-bit) and all my datatables are shown properly. However, when I open in Firefox 49.0 it creates an unnecessary child row out of the last column. This firefox misalignment issue happens for all datatables in my webapp

Please refer to the snapshots of both chrome and firefox.

I then reverted to older versions of datatables and the application worked fine in both Firefox and Chrome

Seems something is broken in your latest version. Can you please identify the issue

Let me know incase you need application login details. I will send them in private as I cannot post login details in public forum.

datatables button with bootstrap tooltip

$
0
0

so i create button for interaction into datatables like this....

  buttons: [
                {
                    text: '<i class="fa fa-plus"></i> <u>A</u>dd',
                    titleAttr: 'Add New Entry',
                    key: {
                        altKey: true,
                        key: 't'
                    },
                    action: function(){
                        window.location.href = "{{URL::to('admins/'.$kelas.'/create')}}";
                    }
                }
]

but i somewhat find some limitation by creating button like this... since i can't add some custom attribute like now i want to add bootstrap tooltip and it is very easy just add "data-toggle" and "data-placement" into the button so it will be like this
<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Tooltip on top">Tooltip on top</button>
but i can't find any way to add those attribute into it... so please anyone know how to deal with it? or maybe there is another work around ?

is changing the value of a cell possible?

$
0
0

hi,

it really surprises me that something so basic is so complicated in datatables. i checked a lot of the related examples, but the whole library is just a huge mess.

i am also very perplexed about the different methods of selecting a row. somehow there is an extension for this but there is also some internal support for selecting stuff. should i use the select extension?

Multi Select DropDown in row disappears on page change or filter

$
0
0

I have a form inside each row of my datatable to select different printing options passing the row id to a print page. The multi select dropdown works fine however, when I change pages or filter the dropdown disappears. However all other buttons remain.

                     $(document).ready(function () {
                            $('#workorder').DataTable({
                                //display columns
                                "columns": [
                                    //display action buttons
                                    {"mData": "idWorkOrder",
                                        "mRender": function ( data, type, row ) {
                                            return '<form method="POST" action="print.php">' +
                                                '<select multiple class="selectpicker" data-width="80px" data-style="btn-info"  data-actions-box="true" id="multipleSelect" name="pages[]"> ' +
                                                '<option disabled selected> Pages </option> ' +
                                                '<option value="1" selected>Haight Cover Sheet</option> ' +
                                                '<option value="2" selected>Set Cover Sheet</option> ' +
                                                '<option value="3" selected>Roofing Work Order</option>' +
                                                '<option value="4" selected>Roofing Subcontractor Pay Request</option> ' +
                                                '<option value="5" selected>Job Site Hazard Assessment Roofing</option> ' +
                                                '<option value="6" selected>Job Site Checklist Roofing</option> ' +
                                                '<option value="7" selected>Subcontractor Checklist Roofing</option> ' +
                                                '<option value="8">Siding Work Order</option> ' +
                                                '<option value="9">Siding Subcontractor Pay Request</option> ' +
                                                '<option value="10">Job Site Hazard Assessment Siding</option> ' +
                                                '<option value="11">Job Site Checklist Siding</option> ' +
                                                '<option value="12">Subcontractor Checklist Siding</option> ' +
                                                '<option value="13">Gutters Work Order</option> ' +
                                                '<option value="14">Gutter Subcontractor Pay Request</option> ' +
                                                '<option value="15" selected>Magnet Sheets</option> ' +
                                                '</select><a href=print.php?idWorkOrder='+row.idWorkOrder+' data-toggle="tooltip" title="PRINT" target="_blank"><button class="btn btn-info btn-sm"><span class="glyphicon glyphicon-print" aria-hidden="true"></span></button></a></form> '+
                                                '<a href=update.php?idWorkOrder='+row.idWorkOrder+' data-toggle="tooltip" title="EDIT"><button class="btn btn-warning btn-sm"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button></a> ' +
                                                '<a href=delete.php?idWorkOrder='+row.idWorkOrder+' data-toggle="tooltip" title="DELETE"><button class="btn btn-danger btn-sm"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button></a>';
                                        }
                                    },
                                    {"data": "cFirstName"},
                                    {"data": "cLastName"},
                                    {"data": "wRoofContract", render: $.fn.dataTable.render.number( ',', '.', 0, '$' )},
                                    {"data": "wSidingContract", render: $.fn.dataTable.render.number( ',', '.', 0, '$' )},
                                    {"data": "wGutterContract", render: $.fn.dataTable.render.number( ',', '.', 0, '$' )}
                                ],
                                "processing": true,
                                "serverSide": true,
                                "responsive": true,
                                "ajax": {
                                    url: 'datatables.php',
                                    type: 'POST'
                                }
                            });
                        });

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

1.10.12 Scroller prefetches only 9 rows

$
0
0

I am using the latest versions of DataTables and this plugin fetched from the CDN last night.

scroller.displayBuffer is at its default of 9, but only 9 records are prefetched when the table loads. According to the documentation page that means that _scroller _thinks there is only one row: 9 * 1 = prefetch 9 rows.

This occurs even when all scroller options are default and the row height has not been changed through CSS tinkering.

Also, even with scroller.boundaryScale set to .1 the plugin does not fetch new data from the server until I scroll passed rows 50 to 70. This means rows 10 through 51+ are blank after the table initially loads. I semi-fixed this by setting boundaryScale to zero, but this is not feasible in a production environment and still does not prefetch enough records to fill the height of the table.

Options:

"autoWidth": false,
"serverSide": true,
"processing": true,
"scrollY": 400,
"ajax": {
    url: "index.php",
    type: "GET",
    "data": function (d) {
        d.what = "list_clients";
        d.include = input_cancelled.prop("checked");
    },
    "cache": true
},
"scrollCollapse": true,
"scroller": true,
/*"scroller": {
    loadingIndicator: true,
    displayBuffer: 9,
    boundaryScale: .1
},*/
"deferRender": true

TD width not the same as TH width

$
0
0

Here's my initialization code:
$('#table1').DataTable({
"scrollX": true,
"autoWidth": true,
"columnDefs": [
{ "width": "20%", "targets": 0 }
],
destroy: true,
processing: true,
serverSide: true,
ajax: {
url: '{!! route("datatablesss.data") !!}',
method: 'POST'
},
columns: [
{data: 'pic', name: 'pic'},
{data: 'first_name', name: 'first_name'},
{data: 'last_name', name: 'last_name'},
{data: 'dob', name: 'dob'},
{data: 'gender', name: 'gender'},
{data: 'email', name: 'email'},
{data: 'phone', name: 'phone'},
{data: 'NID', name: 'NID'},
{data: 'state', name: 'state'},
{data: 'city', name: 'city'},
{data: 'address', name: 'address'},
{data: 'country', name: 'country'},
{data: 'action', name: 'action'}

                    ],
                    initComplete: function () {
                        this.api().columns().every(function () {
                            var column = this;
                            var input = document.createElement("input");
                            $(input).appendTo($(column.footer()).empty())
                            .on('change', function () {
                                column.search($(this).val()).draw();
                            });
                        });
                    },
                    "columnDefs": [{
                        "defaultContent": "-",
                        "targets": "_all"
                      }]
                });

How can fix this :(

Using FontAwesome for row-details expandable button

$
0
0

Hi everyone,

I'm trying to use a FontAwesome icon like 'fa fa-plus-circle" for my row-details instead of the default green/red one given in the example:

datatables.net/examples/server_side/row_details.html

I know i'm supposed to put the icon in an <i> tag, but can't figure out how to do this with just the "class" option exposed on the column. When I try to just do like

"class": "fa fa-plus-circle"

It'll show something like what I've attached, which is messed up, as opposed to just using a .png, which works fine.

Here's my debug code: opaviv

Thanks for your help!


Sort by star rating

$
0
0

Hello. I have an input field that displays a number of stars and I would like to sort by the number of stars highlighted. Can't seem to make this work. Here is my HTML:

<table class="table table-striped" id="homeTable" >
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Username)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.OverallRating)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TotalRatings)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Username)
                </td>
**                <td>
                    @{double score = item.OverallRating; }
                    <input id="input-id" type="number" value="@score" class="rating" data-size="xs" name="OverallRating" data-readonly="true" data-show-clear="false">
                </td>**
                <td>
                    @Html.DisplayFor(modelItem => item.TotalRatings)
                </td>
                <td>

                    @Html.ActionLink("Details", "SeeContractorReviews", new { id = item.ID })

                </td>
            </tr>
        }
   </tbody>
</table>

Any idea how I can get this to work?

How to achieve true column width? - setting overwritten by 5px padding for td

$
0
0

The table should have a fixed column style. Styling the table using:

"columnDefs": [
            {"targets": 0, "width": "25px"}

did not yield in the desired result.

It looks like the style for td includes padding of 5px which is screwing with the width setting.

Is there a setting to eliminate this padding - or is editing the style sheet the only way?

Scrolly: Table width changed when not enough rows

$
0
0

The table is styled for a scroll bar enabled view.

If there are not enough rows, the table collapses and the scroll bar disappears. Good!

However, once this happens, the table width is adjusted and is now taking the space including what was taken by the scroll bar.

Since there are 3 tables on the website, the 'collapsed' ones don't not align anymore with the 'non collapsed' ones.

Is there a way to keep the table width and 'add the scroll bar' if needed?

Losing proper column order when switching columns and sorting

$
0
0

Hi,

I'm using server-side version of datatables.
Everything works fine except when I switch columns and use sorting. All the data in rows comes always in the same order in rows (in wrong columns).
When I click sort button, state_save.php and state_load is executed.
When I reload page everything works fine as state_load.php and load_data.php is executed.
It's like the datatables "don't" know what is the current order of columns.

index:

<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
    var table = $('#example').DataTable( {
                serverSide: true,
                ajax: 'js/datatables/php/load_data.php?login_uprawnienia={/literal}{$login_uprawnienia}{literal}&id_user={/literal}{$login_id_user}{literal}&id_tabeli=1',
                "processing": true,
        fixedHeader: true,
        "bStateSave": true,
          "stateSaveCallback": function (settings, data) {
            // Send an Ajax request to the server with the state object
            $.ajax( {
              "url": "js/datatables/php/state_save.php?id_user={/literal}{$login_id_user}{literal}&id_tabeli=1",
              "data": data,
              "dataType": "json",
              "type": "POST"
            } );
          },
          "stateLoadCallback": function (settings) {
            var o;
         
            // Send an Ajax request to the server to get the data. Note that
            // this is a synchronous request since the data is expected back from the
            // function
            $.ajax( {
              "url": "js/datatables/php/state_load.php?id_user={/literal}{$login_id_user}{literal}&id_tabeli=1",
              "async": false,
              "dataType": "json",
              "success": function (json) {
                o = json;
              }
            } );
         
            return o;
          }
    } );
 
    new $.fn.dataTable.ColReorder( table );
} );
</script>

I tried to change ssp.class:

static function data_output ( $columns, $data )
    {
        $out = array();

        for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
            $row = array();
                        $row2 = array();

            for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) {
                $column = $columns[$j];

                // Is there a formatter?
                if ( isset( $column['formatter'] ) ) {
                    $row[ $column['dt'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i] );
                                        //$row2
                                        
                                }
                else {
                    $row[ $column['dt'] ] = $data[$i][ $columns[$j]['db'] ];
                                        $row2[ $column['dt2'] ] = $data[$i][ $columns[$j]['db'] ];
                }
            }

            $out[] = $row;
                        //$out[] = $row2;
        }
                
                $out[0][0] = 'test';

        return $out;
    }

in my 'dt2' is the order of columns in table - in this solution, column are in a good position, but then I switch columns the data "is not going" - it stays in wrong column.

Please help

How to display the cell contents when it is clicked?

$
0
0

`
print "\n table(\"placeholder28\",data,{title:\"<BR><font size=20><b><center>SU<center></b></font><BR>\",colTitles:header})\n";
print " var otable = \$('#placeholder28-table').DataTable({ \n";
#print " retrieve: true, \n";
print " });
\n";

print "\$(\'#placeholder28-table tbody tr\').on(\'click\', \'td:nth-child(10)\', function (f) {

\n";
#print " var tr = \$(this).closest(\'tr\');

\n";

#print " var row = otable.row(tr);\n"
print "var cell=otable.cell(this);

\n";

print "\n var js_hash = { ";
foreach $user (keys %pend_reason_hash) {
    $counter=0;
    $value="<b>Reasons</b>:<br>"; 
    $value .="$pend_reason_hash{$user}";                      
    print "\"$user\":\"$value\",";
    $value="";
}
print "}; \n";

`

Viewing all 35272 articles
Browse latest View live