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

get data from input element in table after change page

$
0
0

Hi,
I tri to use my function to export all input elements in datatables (same function of datatables with few changes), but but the problème is that whene i change an element and change page, if clic export the vale of element changed is not correcte. i have the initial data.
Can you help me ?
sorry about my English :)

code :

$.fn.dataTable.Api.register( 'buttons.exportData()', function ( options ) {
if ( this.context.length ) {
var dt = new $.fn.dataTable.Api(this.context[0]);

            var _exportTextarea = $('<textarea/>')[0];
            var config = $.extend( true, {}, {
                rows:           null,
                columns:        '',
                modifier:       {
                    search: 'applied',
                    order:  'applied'
                },
                orthogonal:     'display',
                stripHtml:      true,
                stripNewlines:  true,
                decodeEntities: true,
                trim:           true,
                format:         {
                    header: function ( d ) {
                        return strip( d );
                    },
                    footer: function ( d ) {
                        return strip( d );
                    },
                    body: function ( d ) {
                        return strip( d );
                    }
                }
            }, options );

            var strip = function ( str ) {
                if ( typeof str !== 'string' ) {
                    return str;
                }

                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;
                }
                if ($.isNumeric(str.replace( / /g, '' ))) {
                    //str = str.replace( / /g, '' );
                    str = str.replace(".", ',' );
                }
                return str;
            };


            var header = dt.columns( config.columns ).indexes().map( function (idx) {
                var el = dt.column( idx ).header();
                return config.format.header( el.innerHTML, idx, el );
            } ).toArray();

            var footer = dt.table().footer() ?
                dt.columns( config.columns ).indexes().map( function (idx) {
                    var el = dt.column( idx ).footer();
                    return config.format.footer( el ? el.innerHTML : '', idx, el );
                } ).toArray() :
                null;

            var rowIndexes = dt.rows( config.rows, config.modifier ).indexes().toArray();
            var selectedCells = dt.cells( rowIndexes, config.columns );
            var cells = selectedCells
                .render( config.orthogonal )
                .toArray();
            var cellNodes = selectedCells
                .nodes()
                .toArray();

            var columns = header.length;
            var rows = columns > 0 ? cells.length / columns : 0;
            var body = new Array( rows );
            var cellCounter = 0;

            for ( var i=0, ien=rows ; i<ien ; i++ ) {
                var row = new Array( columns );
                for ( var j=0 ; j<columns ; j++ ) {
                    var val = cellNodes[cellCounter] ? cellNodes[cellCounter].innerHTML : cells[cellCounter];
                    val = "<div>" + val + "</div>";
                                            // priority is for select if not existe, get data from textbox if existe, if not get data from cell
                    var selectChield = $(val).children('select')[0];
                    if (selectChield) {
                        val = $(selectChield).find('option:selected').text();

                    } else {
                        selectChield = $(val).find('input').filter(':visible').not(':input[readonly]')[0];
                        if (selectChield) {
                            val =  $(selectChield).val();
                        }
                    }
                    row[j] = config.format.body( val, i, j, cellNodes[ cellCounter ] );

                    cellCounter++;
                }

                body[i] = row;
            }

            return {
                header: header,
                footer: footer,
                body:   body
            };
        }
    } );

Getting wrong message "Showing 151 to 144 of 144 records"

$
0
0

When i change the show count value, while on the last page, results in a blank page being added to the page display. & If the last page is selected "No records were found" is displayed and showing count is outside of the range of available records.
"Showing 151 to 144 of 144 records"

Change the left border of some cells : render function ?

$
0
0

Hello,

I'm using DataTables with Bootstrap (Adminlte) and I would like to change the left border of cells which satisfies some conditions.

The content of the cell is rendered using "render:function ( data, type, row ){... return data['text']; }" but I would like to put a 5px green border on the left of the cell IF data['something'] is true.

How can I do that ?

Many thanks in advance,

T.

Server Side Processing + Getting Page Number

$
0
0

Hi,

I would like to do something like the following:

$('#example').dataTable( {
    "processing": true,
    "serverSide": true,
    "ajax": {
                  " url": "GetMoreRows.java",
                   "data": {pgno: table.page.info().page}  //This will send Ajax request with page number
               }
} );

So basically everytime I click the next button, I want to send an AJAX request with custom http parameter as page number.

In all the examples I have seen so far "page.info()" seems to be used only outside of the $.dataTable() function, and it doesn't work inside of the $.dataTable() function. Is there a way to do this?

Thanks,
Anusha

Don't know why one of my columns isn't sorting

$
0
0

Hi, I'm new here (please bear with me!), website is http://www.oxfordbops.co.uk/ - all scripts are within the home document (ie only a little bit of stuff about the date down the bottom and the links to datatables). Not sure why my 'location' column isn't sorting. Any ideas? Thanks

Column Reordering (colReorder) not working when calling the callback function in stateLoadCallback

$
0
0

I'm using colReorder Plugin with DT 1.10.13 and colReorder 1.3.2
When returning the current state like so

stateLoadCallback: function (settings) {
         var o;
         $.ajax( {
             url: 'some_url',
             async: false,
             dataType: 'json',
             success: function (json) {
                 o = json;
             }
         } );
         return o;
     }

everything works just fine and the columns are reordered like saved in the state

But when using the new callback function in this way

$.ajax( {
            url: 'some_url',
            dataType: 'json',
            success: function (json) {
                callback( json );
            }
        } );

nearly everything works just fine except column re-ordering.
They are rendered like the initial state and are saved this way again back to the state.
E.g. instead ordering [0,2,1,3] they are ordered and saved [0,1,2,3]

Excel export and comma decimal

$
0
0

We are using commas for decimal. If we export numbers with commas, for example 1,59 the number exports as 159.

The example works but it also format columns with strings. How can we format only columns with numbers?

{
            extend: 'excel',
            exportOptions: {
                columns: ':visible',
                format: {
                    body: function(data, row, column, node) {
                        return data.replace(',', '.');
                    }

                }
            }
        }

PDF button, column header showing 'x' - from yadcf column search

$
0
0

Hello Alan,

Please provide me a solution for this problem.

Please find (picture 1) - this is how the datatable looks. Each column is using column search filter provided under YADCF plugin.
What is happening (picture 2) is that when you export the grid using cvs or pdf.. it shows that 'x' beside the title.

I have tried, customize option with no luck. Is there a spot in the button.min.js or pdfmaker.min.js file.. which I can edit ?

Thanks for your help.


Converting [object] to URL in column

$
0
0

Hello,

Is there anyone that can take a look at my code and help me figure out why I'm receiving "[object Object]" instead of the URLs I should be receiving.

The data table is under a column called: URL with links formatted as "https://www.google.com".

Attached is what is rendered to the end user.

I attempted to follow a previous thread on this issue but im not understanding hope the issue was resolved. Please assist!
https://datatables.net/forums/discussion/27167/how-do-get-data-in-row-datatable

I added the following code which is now presenting me a link to object object.

"https://cloudsites.XXXX.com/sites/XXXXXX/SitePages/[object%20Object]"

{ "mData": "URL",
"mRender": function ( data, type, full )
{
return '<a href="'+data+'">Link</a>';
}
},

<script language="javascript">

$(document).ready(
function(){

// ajax call to get the list data using REST
var call = $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('TeamLinks')/items?$top=200",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});

// this gets called when the AJAX completes.
// this populates the table created above

call.done(function (data,textStatus, jqXHR){
$('#example').dataTable({
"bDestroy": true,
"bProcessing": true,
"aaData": data.d.results,
"aoColumns": [
{ "mData": "br3e" },
{ "mData": "Comments" },
{ "mData": "URL" },
{ "mData": "Platform" }
],
dom: 'T<"top"if>rt<"bottom"lp><"clear">',
        tableTools: {
            "sSwfPath": "/sites/GPNOC/Style Library/swf/copy_csv_xls_pdf.swf"
        }
});
});


// Render clickable HTML

// called if the AJAX fails

call.fail(function (jqXHR,textStatus,errorThrown){
   alert("Error retrieving Tasks: " + jqXHR.responseText);
});
}

  );

</script>

Multiple DataTables on same page via Sharepoint 2013

$
0
0

Hey guys,

Any idea how I can call two separate Sharepoint list to two different tables on the same page?

I currently have a JS file with the below code that works well with my TeamLinks list but I would like to add another datatable to our homepage thats linked to my Phonebook list in a different web part.

Can anyone help?


// ajax call to get the list data using REST var call = $.ajax({ url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('TeamLinks')/items?$top=200", type: "GET", dataType: "json", headers: { Accept: "application/json;odata=verbose" } }); // this gets called when the AJAX completes. // this populates the table created above call.done(function (data,textStatus, jqXHR){ $('#example').dataTable({ "ordering": true, "info": false, "bDestroy": true, "bProcessing": true, "aaData": data.d.results, "aoColumns": [ { "mData": "Title"}, { "mData": "Notes" }, { "mData": "Link", "mRender": function ( data, type, full ) {return '<a href="'+data+'" target="_blank">Here</a>';} } ], dom: '<"top"if>rt<"bottom"lp><"clear">', tableTools: { "SwfPath": "/sites/XXNOC/Style Library/swf/copy_csv_xls_pdf.swf" } }); });

rowCallback + responsive

$
0
0

Hello,

I'm trying to use rowCallback https://datatables.net/reference/option/rowCallback
and responsive collapsible columns https://datatables.net/extensions/responsive/
at the same time.

The problem is that when a column collapses (because the screen is not wide enough), the displayed value is the original value, not the value that was defined in the fnRowCallback like this:

$('td:eq(1)', nRow).html( '<a href="'+json.url+'" >link</a>' );

Another issue is that you cannot sort on a column filled like this.

Anyone knows how to deal with that?
How do you really add data to your table with a callback (ajax request in my case)?

SHOW all tabels in MySQL database into Datatable, How To?

$
0
0

Hi, I want to load all tables saved in one mysql databese into one datatable, how I can do this?
I tried replacing the SQL query with "SHOW TABLES FROM $dbname" in ssp.class.php but it didn't work. I just need the mysql tables name loaded in one datatable.

Any help is much appreciated. :'(

Delete row not working on joined table since editor 1.6.

$
0
0

Check official link for example joinLinkTable and try to delete a row.
The returned error is: 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.id' in 'where clause'

On our server, we downgraded to 1.5 and it is working without problems.

Moment.js issue

$
0
0

Hi Allan,

similar to the issue I had with format 'L' there is another problem when I trie to use format 'LT'.
LT should be this for German dates: LT: 'HH:mm' and this for English UK dates: LT : 'HH:mm'. Thank god it happens to be the same in this case! For that reason I hard coded it now like this:

{
                label: "Bid Period End Time:",
                name:  "bidEndTime",
                attr: {
                    class: timeMask
                },
                type:  "datetime",
                def:   function () { return endOfDay },
                format:  'HH:mm',

            }

I would prefer to use format: 'LT' because I will be in trouble once I'll add an additional language if I do it like above.
If I use format 'LT' a date picker opens instead of the time picker. Probably becaus of the initial 'L'?! Do you have a fix for this please.

Datetime field not showing error message from server

$
0
0

Hi! I'm running into an issue where I'm sending down an error message in the fieldErrors array in json to a datetime field, but the only text displaying in the editor-datetime-error div is 'Error'.

It's finding the correct field and setting an error, but the message doesn't seem to be inserted. Any ideas on what I might be doing wrong?


Quill - saving the formatted text

$
0
0

I have created a datatable using the online generator, and added Quill to the .js file.

"label": "Comment:",
    "name": "comment",
        "type": "quill"

How do I get it to keep the formatted text upon submit.? At the moment it just saves everything without spaces etc.

DataTables Editor and Django

$
0
0

I have successfully implemented the DataTables Editor Bootstrap example from this site in my Django project. I use a forloop.counter to identify each row. That populates to popup as shown in the attached image.

        <tbody>
            {% for row in queryset %}
            <tr id=forloop.counter> <!-- Needed for DataTables row identification -->
                <td>{{ row.code }}</td>
                <td>{{ row.description }}</td>
            </tr>
            {% endfor %}
         </tbody>

Successful only so far I should say...

My problem is I do not know how to replace the PHP code in the example provided on this site with something that will achieve the same result in Django. The disconnect for me is how to setup the Ajax, JSON, etc. I can get Ajax to work in Django using a Django form with it's own submit button, but I've not figured out how to do same with the DataTables Editor form (see image) and the JSON part.

The solution is likely trivial and I'll kick myself once I see it, but I've not been able to locate anything on the Internet, in the forums, etc. that speaks to this.

 $(document).ready(function() {
    $(".dropdown-toggle").dropdown();
  });

  $(document).ready(function edit_skus() {

    var editorCM = new $.fn.dataTable.Editor( {
        //ajax: "",
        table: "#theader",
        fields: [ {
                label: "CODE:",
                name: "CODE"
            }, {
                label: "DESCRIPTION:",
                name: "DESCRIPTION"
            }]
    } );

    if ( !$.fn.dataTable.isDataTable( '#theader' ) ) {
        var table = $('#theader').DataTable( {
            lengthChange: false,
            //ajax: "",
            columns: [
                { data: "CODE" },
                { data: "DESCRIPTION" }
            ],
            select: true
        } );
    }

    // Display the buttons
    new $.fn.dataTable.Buttons( table, [
        { extend: "create", editor: editorCM },
        { extend: "edit",   editor: editorCM },
        { extend: "remove", editor: editorCM }
    ] );

    table.buttons().container()
        .appendTo( $('.col-sm-6:eq(0)', table.table().container() ) );

    $('#theader tfoot th').each( function () {
       var title = jQuery(this).text();
       $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
   } );


   // Apply the search
   table.columns().every( function () {
       var that = this;

       $('input', this.footer() ).on( 'keyup change', function () {
           if ( that.search() !== this.value ) {
               that
                   .search( this.value )
                   .draw();
           }
       } );
   } );

} );

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

Table with multiple underscores fails to return integer values

$
0
0

I'm noticing strange behavior with Editor 1.6.1 for PHP. When I set up my PHP script to process the Editor, I only see some values being returned in the table. They happen to be only the varchar fields from the table. All integer and char fields are returning as NULL in the debug console. I have another Datatable displaying integer values just fine. After troubleshooting everything including leftJoins, where clause, and commenting out individual fields one by one, I determined that the issue seemed to lie with the table name.

Here is a bit about my setup: I'm using SQL Server 2012 R2 as the database back-end, PHP 5.4.16 running on Apache 2.4.6. Also using Bootstrap 3.3.7 and jQuery 3.1.0 scripts, but I imagine that doesn't matter much in this case. I just want to provide a complete picture to my environment.

I'll provide my server-side code to give an idea of what works and what doesn't:

This works but integer and char fields return as null values (data is actually not returned from the DB, it's not just missing from the table):

Editor::inst( $db, 'dynamic_sku_config, 'id' )
    ->fields(
        Field::inst( 'dynamic_sku_config.product_family_id' )
            ->options( Options::inst()
                ->table( 'product_family' )
                ->value( 'id' )
                ->label( 'name' )
            ),
        Field::inst( 'dynamic_sku_config.component_type_id' )
            ->options( Options::inst()
                ->table( 'component_type' )
                ->value( 'id' )
                ->label( 'name' )
            ),
        Field::inst( 'dynamic_sku_config.ordinal_position' ),
        Field::inst( 'dynamic_sku_config.following_delimiter' ),
        Field::inst( 'dynamic_sku_config.min_components' ),
        Field::inst( 'dynamic_sku_config.max_components' ),
        Field::inst( 'dynamic_sku_config.action' ),
        Field::inst( 'product_family.name' ),
        Field::inst( 'component_type.name' )
    )
    ->leftJoin( 'product_family', 'product_family.id', '=', 'dynamic_sku_config.product_family_id' )
    ->leftJoin( 'component_type', 'component_type.id', '=', 'dynamic_sku_config.component_type_id' )
    ->where( 'dynamic_sku_config.product_family_id', $_POST['selectedProductFamily'], '=' )
    ->process( $_POST )
    ->json();

In the above example, here are the database field types (each table has a field named "id" as an integer primary key):

dynamic_sku_config
product_family_id, int
component_type_id, int
ordinal_position, int
following_delimiter, char(1)
min_components, int
max_components, int
action, varchar(16)

component_type
name, varchar(50)

product_family
name, varchar(50)

Interestingly, since I'm joining to other tables for product_family and component_type, the Datatable will display the name field from the joined tables (product_family_id and component_type_id are not displayed to the user). The action field is also displayed as it is varchar. Every other field is blank due to null values coming back from the server.

I copied the contents of dynamic_sku_config into another table called dskutest. Here is the modified code (identical to above except for the table name):

Editor::inst( $db, 'dskutest', 'id' )
    ->fields(
        Field::inst( 'dskutest.product_family_id' )
            ->options( Options::inst()
                ->table( 'product_family' )
                ->value( 'id' )
                ->label( 'name' )
            ),
        Field::inst( 'dskutest.component_type_id' )
            ->options( Options::inst()
                ->table( 'component_type' )
                ->value( 'id' )
                ->label( 'name' )
            ),
        Field::inst( 'dskutest.ordinal_position' ),
        Field::inst( 'dskutest.following_delimiter' ),
        Field::inst( 'dskutest.min_components' ),
        Field::inst( 'dskutest.max_components' ),
        Field::inst( 'dskutest.action' ),
        Field::inst( 'product_family.name' ),
        Field::inst( 'component_type.name' )
    )
    ->leftJoin( 'product_family', 'product_family.id', '=', 'dskutest.product_family_id' )
    ->leftJoin( 'component_type', 'component_type.id', '=', 'dskutest.component_type_id' )
    ->where( 'dskutest.product_family_id', $_POST['selectedProductFamily'], '=' )
    ->process( $_POST )
    ->json();

All fields are now populating in the Datatable with no changes to the front-end page. I should point out that tables with a single underscore in them (e.g., product_family, component_type, etc.) work without issue. I hadn't captured the actual query being sent to the SQL Server but I could probably get it if it would be of interest or provide any clues as to why this might be happening.

I didn't see anyone else with this same issue on the forums, so I thought I would post it myself, either as a workaround for anyone encountering the same issue (or maybe a bug fix for a future release!).

Date field localization issue

$
0
0

I have a CRUD management application, which I've obtained using the DTE generator. One of the fields is of date type, which I want to give a specific format, with these elements:

  • Moment.js (included in the whole DTE package by generator)
  • Plugin datetime.js (written by Allan Jardine)
  • Plugin datetime-moment.js (written by Allan Jardine)

In file 'table.mapi.js' (DTE generator), I add these lines

moment.locale('es'); // Chage locale to spanish
$.fn.dataTable.moment( 'ddd, D MMM YYYY', 'en' ); // Call function to give format to datetime field -- note that if I put 'es' on locale parameter, order doesn't work (some plugin compatibility issue?)

after $(document).ready(function() {

then, I define ('fields' param of var editor) the following:

"label": "Fecha:",
"name": "fecha",
"type": "datetime",
"def": function () { return new Date();},
"format": "ddd, D MMM YYYY",
"opts": { "showWeekNumber": false, "momentLocale": 'es' }

and

"data": "fecha",
"render": function ( data, type, full, meta ) { if (type === 'display') { if (data) { var mDate = moment(data); data = (mDate && mDate.isValid()) ? mDate.format("LL") : ""; } } return data; }

('columns' param of datatables), to get date displayed on large format.

Till now, all this works fine. The problem arrives on "New" record button's hand, when I fill in the fields (selecting desired date on datepicker) and then I press "Save" button, validator shows the following error:

"Date is not in the expected format", and, obviously, doesn't perform the op (save data to mysql db).

In addition, when I select one row, in order to edit its data, the modal edit form shows the fields; but date field is still on default locale ('en').

I suposse this is due to issues with format specified in date validator, since I've left the defaults created by DTE generator (except empty field validation, that's been customized), so:

Field::inst( 'fecha' )
->validator( function ( $val, $data, $opts ) { return empty( $val ) ? 'Este es un campo requerido' : true; } )
->validator( 'Validate::dateFormat', array( 'format'=>'D, j M Y' ) )
->getFormatter( 'Format::date_sql_to_format', 'D, j M Y' )
->setFormatter( 'Format::date_format_to_sql', 'D, j M Y' ),

What's the correct validation in this case? Do I need configure some kind of i18n on PHP settings in validation module, such as Moment 'locale'?

Thanks in advance

Where clause Or operators and grouping

$
0
0

hi ,
i am using Where clause Or operators in my php file,it is displaying correctly,but when iam updating the changes are not reflecting back ,but when i use only where clause without any or operators it is working fine

'Below is my php file
<?php

include( "../editor/php/DataTables.php" );

use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Upload,
DataTables\Editor\Validate;

// Build our Editor instance and process the data coming from _POST
$editor=Editor::inst( $db, 'userdetails','user_id' )
->fields(
Field::inst( 'firstname' )->validator( 'Validate::notEmpty' ),
Field::inst( 'lastname' )->validator( 'Validate::notEmpty' ),
Field::inst( 'email' )->validator( 'Validate::notEmpty' ),
Field::inst( 'company_name' )->validator( 'Validate::notEmpty' ),
Field::inst( 'role_name' )
->options( 'roledetails', 'role_name', 'role_name' )
->validator( 'Validate::notEmpty' ),
Field::inst( 'phoneNo' )
->validator( 'Validate::numeric' )
->setFormatter( 'Format::ifEmpty', null ),
Field::inst( 'active' ),
Field::inst( 'stype' )
->options( 'subscription', 'sub_type', 'sub_type' )
->validator( 'Validate::notEmpty' )

);

/* need to select rows where rolenum or stype is null*/

    $editor->where( function ( $q ) {
        $q
        ->where( 'role_name', null )
        ->or_where( function ( $r ) {
            $r->where( 'stype', null  );

        } );
    } );

$editor ->process( $_POST );
$editor  ->json();
?>
Viewing all 81402 articles
Browse latest View live


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