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

Restore original data after $.fn.dataTable.ext.search.push

$
0
0

how I can restore origianal information after $.fn.dataTable.ext.search.push

i am tryn this but doesn work, plis help me!!

i use a checkbox to filter values > 0 in one colum or not

if($("#test5").is(':checked')) {
                         $.fn.dataTable.ext.search.push(
                                function( settings, searchData, index, rowData, counter ) {
                                    var min = 0.00;
                                    var valor = parseFloat( searchData[6]); // using the data from the 6th column
                                    if (( isNaN( min )) || ( valor != min))
                                    {
                                        return true;
                                    }
                                    return false;
                                }
                            );
                    }

                     else {
                        $.fn.dataTable.ext.search.push(
                            function( settings, searchData, index, rowData, counter ) {
                                var min = 0.00;
                                var valor = parseFloat( searchData[6]); // using the data from the 6th column
                                    return true;
                            }
                        );
                    }

ajax returned data not binding with jquery datatable pluging

$
0
0

I have a jquery datatable UI that I want to bind with my data returned using an ajax call. The view on which I want to display uses a partial view. On my controller the I return a json type. I can get the data from the ajax call but IE downloads it, intead of binding the data with the jquery datatable UI.

I tried to add the jquery script on both the main view and the partial view but none is working. Any input is much appreciated.

Here is my code on my controller:

[HttpPost]
        public ActionResult Index(LShViewModel model, string Command)
        {
            if (Command == "Search")
            {
                //model.CountryIdSelected = model.CountryID;
                //model.CountryIdSelected = null;
                var results = helper.SearchUsers(model.UserName, model.EmailAddress, model.FirstName, model.LastName,  model.CountryID);
                if (model.SearchRecords == null)
                {
                    model.SearchRecords = new List<SearchUserResult>();
                }

                foreach (var result in results)
                {
                    model.SearchRecords.Add(result);
                }
                //model.SearchRecords = results;

            }
            model.States = new SelectList(helper.ListStates(model.CountryID), "ID", "Name");
            model.Countries = new SelectList(helper.ListCountries(), "ID", "Name");
            model.CountryIdSelected = model.CountryID;

           // jsonResult.maxJsonLength = int.MaxValue;
            return Json(model);


        }

here is the scrip on my index page:

<script>
    $('#search').click(function () {
        $('#searchResults').dataTable({
            "ajax": {
                "url": "/Learner/Index",
                "dataSrc": "",
                "dataType": "json",
                "success": function (data) {
                    $('#searchResults').dataTable({

                        data: data,
                        columns: [

                            { 'data': 'UserName' },
                            { 'data': 'Email' },
                            { 'data': 'FirstName' },
                            { 'data': 'MiddleName' },
                             { 'data': 'LastName' },
                            { 'data': 'Address' },
                            { 'data': 'City' },
                            { 'data': 'StateID' },
                              { 'data': 'PostalCode' },
                            { 'data': 'Phone' },
                             { 'data': '' },


                        ]
                    })
                }
            }
        });

        var table = $('#searchResults').dataTable();
        table.fnClearTable();
        table.fnDraw();
        $.ajax({

            url: '/Learner/Index',
            method: 'post',
            dataType: 'json',
            dataSrc: "",
            success: function (data) {
                $('#searchResults1').dataTable({

                    data: data,
                    columns: [

                        { 'data': 'UserName' },
                        { 'data': 'Email' },
                        { 'data': 'FirstName' },
                        { 'data': 'MiddleName' },
                         { 'data': 'LastName' },
                        { 'data': 'Address' },
                        { 'data': 'City' },
                        { 'data': 'StateID' },
                          { 'data': 'PostalCode' },
                        { 'data': 'Phone' },
                         { 'data': '' },


                    ]

                });
            }


        });



    })
</script>

here is my partial view:

```

Search Results

<div class="col-md-12">
    <table id="searchResults" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            @*<th> Select</th>*@
            <th>Username</th>
            <th>Email</th>
            <th>First Name</th>
            <th>MI</th>
            <th>Last Name</th>
            <th>Address</th>
            <th>City</th>
            <th>State</th>
            <th>Zip</th>
            <th>Phone</th>
            <th></th>
            @*<th>CE Type</th>*@
        </tr>
    </thead>
    <tbody>
        @{
            for (var i=0; i < Model.SearchRecords.Count; i++)
            {
                <tr>
                    <td>
                        @*@Html.CheckBox("Select")*@
                        @Model.SearchRecords[i].UserName
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].CountryID)
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].CountryCode)
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].PersonID)
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].Email)
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].FirstName)
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].MiddleName)
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].LastName)
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].Address)
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].City)
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].UserName)
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].PostalCode)
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].Phone)
                        @*@Html.HiddenFor(modelItem => Model.SearchRecords[i].ACPEID)
                        @Html.HiddenFor(modelItem => Model.SearchRecords[i].AAVSBID)*@
                        @*@Html.HiddenFor(modelItem => Model.SearchRecords[i].CH)*@




                        @*@Html.HiddenFor(modelItem => Model.SearchRecords[i].PhysicianTypeID)*@
                    </td>
                    <td>@Model.SearchRecords[i].Email</td>
                    <td>@Model.SearchRecords[i].FirstName</td>
                    <td>@Model.SearchRecords[i].MiddleName</td>
                    <td>@Model.SearchRecords[i].LastName</td>
                    <td>@Model.SearchRecords[i].Address</td>
                    <td>@Model.SearchRecords[i].City</td>
                    <td>@Model.SearchRecords[i].StateCode</td>
                    <td>@Model.SearchRecords[i].PostalCode</td>

                    @if (Model.SearchRecords[i].Phone != "INVALID")
                    {
                         <td>@Model.SearchRecords[i].Phone</td>
                    }

                     @if (Model.SearchRecords[i].Phone == "INVALID")
                    {
                         <td> <text></text></td>
                    }

                    <td>
                        <div class="dropdown">
                            <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
                                Manage

                            </button>
                            <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
                                <li role="presentation"><a role="menuitem" tabindex="-1" href="@Url.Action("ViewProfile1", "Learner", new { personid=Model.SearchRecords[i].PersonID})">View Profile</a></li>

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

```

Update data in column of a table with HTML (DOM) sourced data.. ?

$
0
0

Can i do this? No database and no ajax. I have only a table and need to change one column. Now, i have a selected column .. but no have idea how can a edit all cells of a column. Example: plus 50% of a cell value. Thanks

How I can show the tooltips in each cell?

$
0
0

How I can show the tooltips in each cell?

Getting popup edit window on close to refresh table.

$
0
0

Hello,

I am using the editor as inline and as a popup to edit consecutive rows. I would like to refresh the table when the user closes the popup window, but I am not able to get the close event. When I tried "editor.on('close') it executes the refresh just when I open the popup window by pressing the "edit" button. I am also having problems when commenting out the "create" button and get this error "node: inst.s.buttons[ selector ].node".

Any help will be appreciate, thank you and here is my code:

`
var editor; // use a global for the submit and return data rendering
var parKualiDepositID;
var parMerchantConnectGroupID;
var parReconcileNote;
var parReconcileBy;
var parMerchantConnectID;
var param;
var table;

$(document).ready( function() {
var adminID = $('#adminid').val();

editor = new $.fn.dataTable.Editor( {

    ajax: {
        url: "components/merchantDAO.cfc?method=getMerchant&returnformat=json",
        data: function ( d ) {
            d.RecordType = 0;
        },
    },
    table: "#tbParticipants",
    idSrc: 'merchantconnectid',

    fields: [
        {
            label: "Credit Card",
            name: "cardnumber",
            enabled: false
        },
        {
            label: "Kuali Deposit ID:",
            name: "kualidepositid"
        }, {
            label: "Group Name:",
            name: "groupname",
            type: "selectize",
            placeholder: "Select a Group",
         },
        {
            label: "Reconcile Note:",
            name: "reconcilenote"
        }

    ],
    formOptions: {
        main: {
            submit: 'changed'   // will submit only if there are changes
        }
    }

 } );

 // getGroups function will populate "Group Name" dropdown by passing field name and getting data from DAO
 getGroups( editor.field('groupname') );

 function getGroups( field ){

    var aListObject = new Array();

    $.ajax ({
        type: "GET",
        async: false,
        url: "components/merchantDAO.cfc?method=getMerchantConnectGroup&returnformat=json",

        success: function (options) {
            var obj = JSON.parse(options);

            for (var i = 0; i < obj.options.length; i++) {

                item = {};

                item["label"] = obj.options[i].groupname;
                item["value"] = obj.options[i].merchantconnectgroupid;
                aListObject.push(item);

        }
            field.update( aListObject );
        }

     });

 };

// Disable "Credit Card" field on edit. We just want to show it to the user
editor.field( 'cardnumber').disable();


// Activate an inline edit on click of a table cell
$('#tbParticipants').on( 'click', 'tbody td', function (e) {
    editor.inline( this, { submitOnBlur: true } );
} );

// Handle data before submit edit (update)
editor.on( 'preSubmit', function ( e, data, action ) {
    var KualiDepositID = editor.field( 'kualidepositid' );
    var MerchantConnectGroupID = editor.field( 'groupname' );
    var ReconcileNote = editor.field( 'reconcilenote' );
    parReconcileBy = adminID;

    // loop to get key (id) and if processing many edits
    $.each( data.data, function ( key, value ) {
        parMerchantConnectID = key;
        parKualiDepositID = data.data[key].kualidepositid;
        parMerchantConnectGroupID = data.data[key].groupname;
        parReconcileNote = data.data[key].reconcilenote;
    });


    // Build parameters for component call
    param = 'MerchantConnectID=' + parMerchantConnectID  + '&ReconcileBy=' + parReconcileBy;

    if (KualiDepositID.val()){
        param = param + '&KualiDepositID=' + parKualiDepositID;
    }
    if (MerchantConnectGroupID.val()){
        param = param + '&MerchantConnectGroupID=' + parMerchantConnectGroupID;
    }
    if (ReconcileNote.val()) {
        param = param + '&ReconcileNote=' + parReconcileNote;
    }

    // Execute update
     $.ajax ({

        url: "components/merchantDAO.cfc?method=updateMerchantConnectReconcile&returnformat=json",
        method: "POST",
        data: param,
        success: function(result){

        }

    });

});  // End of 'preSubmit'

editor.on('close', function(e) {

        alert("will close");
           // table.ajax.reload();

});



// Buttons array definition to create previous, save and next buttons in
// an Editor form
var backNext = [
    {
        label: "&lt;",
        fn: function (e) {
            // On submit, find the currently selected row and select the previous one
            this.submit( function () {
                var indexes = table.rows( {search: 'applied'} ).indexes();
                var currentIndex = table.row( {selected: true} ).index();
                var currentPosition = indexes.indexOf( currentIndex );

                if ( currentPosition > 0 ) {
                    table.row( currentIndex ).deselect();
                    table.row( indexes[ currentPosition-1 ] ).select();
                }

                // Trigger editing through the button
                table.button( 1 ).trigger();
            }, null, null, false );
        }
    },
    'Save',
    {
        label: "&gt;",
        fn: function (e) {
            // On submit, find the currently selected row and select the next one
            this.submit( function () {
                var indexes = table.rows( {search: 'applied'} ).indexes();
                var currentIndex = table.row( {selected: true} ).index();
                var currentPosition = indexes.indexOf( currentIndex );

                if ( currentPosition < indexes.length-1 ) {
                    table.row( currentIndex ).deselect();
                    table.row( indexes[ currentPosition+1 ] ).select();
                }

                // Trigger editing through the button
                table.button( 1 ).trigger();
            }, null, null, false );
        }
    }
];

  table = $('#tbParticipants').DataTable( {
    responsive: true,
    bPaginate: false,
    dom: "Bfrtip",
    bProcessing: true,
    bServerSide: false,
    bAutoWidth: false,
    bJQueryUI: true,
    //sPaginationType: "full_numbers",
    ajax: {
        url: "components/merchantDAO.cfc?method=getMerchant&returnformat=json",
        data: function ( d ) {
            d.RecordType = 0;
        }
    },

    columns: [

        {   // Responsive control column
            data: null,
            defaultContent: '',
            className: 'control',
            orderable: false
        },
        { data: "merchantconnectid" },
        { data: "cardnumber" },
        { data: "cardtype" },
        { data: "itemamount", render: $.fn.dataTable.render.number( ',', '.', 0, '$' ) },
        { data: "entrymethod" },
        { data: "authcode" },
        {
          /* when passing null to mData we pass the whole row so we can use different fields to format display */
          data: null,
          "mRender": function ( data, type, full, meta ){
                var displayDate =new Date(data.batchdate);
                return displayDate.toLocaleDateString();
                }
        },
        { data: "transdate",},
        { data: "transtime" },
        { data: "refnumber" },
        { data: "roctext" },
        { data: "kualidepositid",
            render: function ( data, type, row ){
                if ( type === 'display' ) {
                    //var numberRenderer = $.fn.dataTable.render.number( ',', '.', 0, '$' ).display;
                    return  data + ' <i class="fa fa-pencil"/>';
                }
                return data;
            }

        },
        { data: "groupname",
            render: function ( data, type, row ){
                if ( type === 'display' ) {
                    //var numberRenderer = $.fn.dataTable.render.number( ',', '.', 0, '$' ).display;
                    return  data + ' <i class="fa fa-pencil"/>';
                }
                return data;
            }
        },

        { data: "reconcilenote",
            render: function ( data, type, row ){
                if ( type === 'display' ) {
                    //var numberRenderer = $.fn.dataTable.render.number( ',', '.', 0, '$' ).display;
                    return  data + ' <i class="fa fa-pencil"/>';
                }
                return data;
            }
        },
        { data: "reconcileby"}
    ],

    select: true,
    buttons: [
        { extend: "create", editor: editor, enabled: false },
        {
            extend: 'selected',
            text:   'Edit',
            action: function () {
                var indexes = table.rows( {selected: true} ).indexes();

                editor.edit( indexes, {
                    title: 'Edit',
                    buttons: indexes.length === 1 ?
                        backNext :
                        'Save'
                } );
            }
        }

// ,
// { extend: "remove", editor: editor, enabled: false }
],

    keys: {
        columns: ':not(:first-child)',
        keys: [ 9 ] // Tab key
    }



} );    // Ending datatable


    // Inline editing on tab focus
    table.on( 'key-focus', function ( e, datatable, cell ) {
    editor.inline( cell.index() );
} );

} ); // Ending document ready
`

How to add custom html field to the editor.

$
0
0

Hi.

I want to show a link based on the cell value that been clicked in the editor,(pic attach).

what is the best way to this?

can I do it via the editor fields array?

Thanks

Wrong payload ajax

$
0
0

Hi,
i have a problem using datatable with an ajax source. The ajax request contain the wrong payload.
I use datatables in version 1.10.12.

I can do the following standalone ajax request:

var getRequest ={"id":-1,"filterName":"assetFilter"};
getRequest =  JSON.stringify(getRequest);

$.ajax({
    type : 'POST',
    url : "http://"+restServer+":"+restPort+"/asset/get",
    data : getRequest,
    dataType : "json",
    contentType : "application/json; charset=utf-8"});

This is a valid call in my environment. I see in the debugger of the browser that everything is fine. The payload of the request is:
{id: -1, filterName: "assetFilter"}
That fits to my expecation.

I get a different payload if i use the following code in my table definition:

ajax :{
    type : 'POST',
    url : "http://"+restServer+":"+restPort+"/asset/get",
    data : getRequest,
    dataType : "json",
    contentType : "application/json; charset=utf-8"}

For my understanding, the code should do exactly the same as the separate ajax call before. But the payload of the request is:
0=%7B&1=%22&2=i&3=d&4=%22&5=%3A&6=-&7=1&8=%2C&9=%22&10=f&11=i&12=l&13=t&14=e&15=r&16=N&17=a&18=m&19=e&20=%22&21=%3A&22=%22&23=a&24=s&25=s&26=e&27=t&28=F&29=i&30=l&31=t&32=e&33=r&34=%22&35=%7D
The var getRequest is not changed in between.

Can someone explain what happens here?

Uncaught TypeError: Cannot read property 'prototype' of undefined

$
0
0

I'm having what seems to be a serious issue with the DataTables Editor. I've stripped it down to only the dataTables.editor.min.js file. I'm sure I'm using the purchased version.

Whenever I include it in a page (in this case VisualForce, part of Salesforce.com) I get the following error in the console (even without adding anything else on the page):
dataTables.editor.min.js:586
Uncaught TypeError: Cannot read property 'prototype' of undefined

This is line that's causing the issue:
(f.DateTime.prototype,{destroy:function(){thisE7;this[(J1d.g8+J1d.h4I+Z0I)](o6+k3+J1d.M5I+J1d.V8+p2I+N2I)(J1d.h4I+d9).empty();this[h1w][J5g]S9w;}

This used to work fine before (last time I checked it was 2 weeks back)..
Do you have any clue what might be causing this?

These are the scripts that I'm loading:

<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.2.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/select/1.2.0/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="{!URLFOR($Resource.datatables_Editor, '/js/dataTables.editor.js')}"></script>


Print only selected rows if there is selected row otherwise all of them

Inline editor, Fixed column is not working on edit with scroll bar

$
0
0

var table =$('#test').DataTable({
dom: "Bfrtip",
scrollX: true,
fixedColumns: {
rightColumns:1
}............................

I need to fix last column. but when I add scrollX: true then its not working when I edit table row. Could be please suggest me?

Remove some search bars from footer

Cannot read property 'Editor' of undefined

$
0
0

Hi, everybody I am new with datatable, and I have this problem that is driving me crazy.
I am working with PHP codeigniter, and it is working wonderfully in Mozilla Firefox, but when I open it in Chrome it always gives me the same error.
"Uncaught TypeError: Cannot read property 'Editor' of undefined".

Please help me.

This are my libraries:

<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/editor/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/editor/dataTables.tableTools.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/editor/editor.bootstrap.css">

<script languaje="javascript" src="<?php echo base_url(); ?>assets/js/editor/jquery.dataTables.js"></script>
<script languaje="javascript" src="<?php echo base_url(); ?>assets/js/editor/dataTables.tableTools.js"></script>
<script languaje="javascript" src="<?php echo base_url(); ?>assets/js/editor/dataTables.editor.js"></script>
<script languaje="javascript" src="<?php echo base_url(); ?>assets/js/editor/editor.bootstrap.js"></script>

This is my datatable:

function dibujaTablaResind(){

     idArea = $("#areaId option:selected").val();
     zona   = $("#zonaArea").val();
     objetivoSele = $("#idObjeResInd option:selected").val();
     var openVals;

        //-------------     CREANDO EL EDITOR       --------------//
            editor = new $.fn.dataTable.Editor({
                "ajax":   "adminActividadPgoa/procesarResInd/"+ idArea+"/"+zona+"/"+objetivoSele,
                "table":  "#resInd",
                "idSrc":  "DATOS.id",
                i18n: {
                create: {
                    "button": "Nuevo",
                    "title":  "<div class='alert alert-info'><strong>Crear Nuevo Resultado - Indicador - Fuente de Verificación</strong></div><div class='info'><strong>NO</strong> ingresar caracteres especiales</div>",
                    "submit": "Crear"
                },
                edit: {
                    "button": "Modificar",
                    "title":  "<div class='alert alert-info'><strong>Modificar Resultado - Indicador - Fuente de Verificación</strong></div>",
                    "submit": "Actualizar"
                },
                remove: {
                    "button": "Eliminar",
                    "title":  "<div class='alert alert-info'><strong>Eliminar Resultado - Indicador - Fuente de Verificación</strong></div>",
                    "submit": "Eliminar",
                    confirm: {
                            _: "<div class='alert'><strong>Esta seguro de eliminar este Resultado Indicador - Fuente de Verificación?</strong></div>",
                            1: "<div class='alert'><strong>Esta seguro de eliminar este Resultado Indicador - Fuente de Verificación?</strong></div>"
                    }
                },
                error: {
                    "system": "<div class='alert'>Un error se ha producido, contacte con el Administrador del Sistema</div>"
                }
            },
            "fields": [
                         {
                             "label":  "Numero",
                             "name":   "DATOS.numero",
                             "type":   "hidden"
                         },
                           {
                             "label":  "Id",
                             "name":   "DATOS.id",
                             "type":   "hidden"
                         },
                         {
                             "label":  "Resultado",
                             "name":   "DATOS.resind_resultado",
                             "type":   "text"
                         },
                         {
                             "label":  "Indicador",
                             "name":   "DATOS.resind_indicador",
                             "type":   "text"
                         },
                         {
                             "label":  "Fuente de Verificación",
                             "name":   "DATOS.resind_fuente",
                             "type":   "text"
                         },
                         {
                             "label":  "Año",
                             "name":   "DATOS.resind_anio",
                             "type":   "hidden"
                         }
                    ]
        });
        //-----------     FIN EDITOR CREADO         -----------------//
        //-----------   MANEJADOR DE INSTANCIAS     -----------------//
        editor.on( 'open', function (){
                    openVals = JSON.stringify( editor.get() );

                })
                .on( 'close', function () {
                    openVals = JSON.stringify( editor.get() );
                    oTable= dibujaTablaResind();
                })
                .on( 'preBlur', function () {
                      if ( openVals !== JSON.stringify( editor.get() ) ) {
                        return confirm( 'You have unsaved changes. Are you sure you want to exit?');
                }
                })
               .on('preSubmit', function(e, o, data, action){
                $.ajax({
                    "url":        '../login/login/get_ajax_is_login',
                    "type":       'POST',
                    data:       {},
                    "dataType":   'json',

                    success:    function(data){
                        if(data.login == false){
                            window.location = "../login/login/restart_login";
                        }

                    }
                });
            });

                    //-------------     CREANDO LA TABLA        --------------//

    oTable = $('#resInd').dataTable({
                "dom": domButton,
                "bSort": false,
                "select": true,
                "bDestroy": true,
                "ajax": "adminActividadPgoa/getResInd/" + idArea+"/"+zona+"/"+objetivoSele,
                "columns": [
                    {"data": "DATOS.numero"},
                    {"data": "DATOS.id", "visible": false},
                    {"data": "DATOS.resind_resultado"},
                    {"data": "DATOS.resind_indicador"},
                    {"data": "DATOS.resind_fuente"},
                    {"data": "DATOS.resind_anio", "visible": false}
                ],
                tableTools: {
                    "sRowSelect": "os",
                    "sSwfPath": "assets/DataTables-1.10.1/extensions/TableTools/swf/copy_csv_xls.swf",
                    "aButtons": [
                        {"sExtends": "editor_create","editor": editor, "sButtonText": "Nuevo",
                                    "formButtons": [
                                    {
                                        "label": 'Cancelar',
                                        fn: function () { this.close(); }
                                    },
                                    'Crear',
                                    ]
                        },
                        {"sExtends": "editor_edit", "editor": editor, "sButtonText": "Editar",
                                    "formButtons": [
                                    {
                                        "label": 'Cancelar',
                                        fn: function () { this.close(); }
                                    },
                                    'Editar',
                                    ]
                        },
                        {"sExtends": "editor_remove", "editor": editor, "sButtonText": "Eliminar",
                                    "formButtons": [
                                    {
                                        "label": 'Cancelar',
                                        fn: function () { this.close(); }
                                    },
                                    'Eliminar'
                                ]
                        }
                    ]
                }
            });

        return oTable;
}

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

How to dynamically create table columns?

$
0
0

Hi all,
I have a stored procedure that returns data. Prior to executing the stored procedure, I do not know the number of columns or the title for each column. I'm trying to create a table to display the data from the stored procedure. In the past, I have just hard coded the header names and brought the data in with something like this:
HorizontalData.php

        $(document).ready(function() {
            $('#HorizontalData_ajax').dataTable( {
                "sAjaxSource": "content/HorizontalData_ajax.php?startdate=<?php echo $startdate;?>&enddate=<?php echo $enddate;?>&description=<?php echo $description;?>",
                "bPaginate": true,
                "processing": true,
                "bDeferRender": true,
                "bAutoWidth": false,
                "bScrollCollapse": true,
                "sScrollY": "250px",
                "bStateSave": true,
                "sDom": '< TC > ftiS',
                "oTableTools": {
                    "sSwfPath": "js/copy_csv_xls.swf",
                    "aButtons":[
                        "copy",
                        "print",
                        {
                            "sExtends":    "collection",
                            "sButtonText": "Save",
                            "aButtons":    [ "xls" ]
                        }
                                ]
                                },
                                 } ).fnSetFilteringDelay();
        } );

    </script>

<div class="clear20"></div>
    <table id="HorizontalData_ajax" class="pretty" border="0">
        <thead>
            <tr>
                <th>Lot</th>
                <th>% +10 mesh</th>
                <th>% -50 mesh</th>
                <th>% Moisture</th>
                <th>Avg 24r Viscosity</th>
                <th>Avg u 10/u0</th>
                <th>Coating: %</th>
                <th>Color</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
            </tr>
        </tfoot>
    </table>


    <?php } ?>

HorizontalData_ajax

 $resultsDescription = odbc_exec($connection, "EXEC CompanyDB.dbo.sp_stored_procedure '$startdate','$enddate','$description'");


$out = array();

while($data = odbc_fetch_array($resultsDescription))
{

    $row = array(
        $data['Lot'],
        $data['% +10 mesh'],
        $data['% -50 mesh'],
        $data['% Moisture'],
        $data['Avg 24r Viscosity'],
        $data['Avg u10/u0'],
        $data['Coating: %'],
        $data['Color']);


          $out[] = $row;
}

echo json_encode(array("aaData" =>$out));
?>

I can't do this, however, because I do not know ahead of time what the data is I'm looking for, the columns names or even the number of columns returned. Any help on how to dynamically create this table is greatly appreciated.

Searching for the exact string (no substrings)

$
0
0

Let's say i have a table with three rows. In one column, i have these vaules

1) coach
2) assistant coach
3) Coach

If i do a search now, all rows return. I don't want that. What I need is two sets of code to do the following operations:

1) to be able to type the word "coach" and only have it return rows 1 and 3.
2) to be able to type the word "coach" and only have it return row 1 (case sensitive)

Let me know if this is possible.

My current code is:

                var stringFilter = $(this).val();
                var myregex = ("\\b" + stringFilter + "\\b");
                $("##add_grid").DataTable().column().columns(7).search(myregex,true,false).draw();

Inline Editor and type = 'select' fields

$
0
0

I'm trying to use a super basic select field with two values 'A' and 'D' with the inline editor.

{
                label: "Statut",
                name: "statut",
                type:  "select",
                options: [
                    { label: "A", value: "A" },
                    { label: "D", value: "D" }
                ]
            }

I would like that either (or both) selecting a value AND/OR pressing the return key trigger a submit event. I'm not fussy!

I've searched and the closest that I have come to a solution was with this post:

https://datatables.net/forums/discussion/22754/im-looking-for-an-example-of-using-an-inline-select

Specifically Allan's reply stating that there's no way to distinguish between the expected return key behaviors. That was a 2014 post and I was wondering if in 2016 there's a solution to achieve that seemingly simple goal?

I've found other more recent posts that I've found are not exactly related to this situation.

I've tried the 'onReturn' and 'submitOnblur' options with no success. The ideal option would be sound like 'onSelect' = 'submit' or submitOnselect = 'true'

    // Activate an inline edit for ENTETE on click of a table cell
    $('#entete').on( 'click', 'tbody td:not(:first-child)', function (e) {
    entEditor.inline( this, {
        submit: 'all'//, //Submit all information even if not changed
        //onReturn: 'submit',
        //submitOnBlur: true
    } );
} );

BTW, everything works fine in the bubble editor.

Thanks in advance.


Low performance on editor.PreCreate server-sive event

$
0
0

Hi Allan,

As part of my web site's business logic, I need to dynamically determine a value to a field called billingId before adding the transaction object to the database. I am taking advantage of the PreCreate event on my .NET Web API Controller as following:

editor.PreCreate += (sender, e) => {
                    Dictionary<string, object> bankTransaction = (Dictionary<string, object>) e.Values["BankTransaction"];

                    var billing = 3; //ToDo: develop custom function to get billingId from DB

                    if (bankTransaction.ContainsKey("billingId") == false)
                        bankTransaction.Add("billingId", billing);
                };

After incluing the code above, the web site seems to have taken a major hit on performance. It is taking 5 secs to update the database. When removing the precreate event, it takes miliseconds.

Are there alternatives or best practice to the code I wrote?

Thanks

Sort Table By Column Removing Styling?

$
0
0

http://celestialcaravan.com/List/

This is the site in question. When I add the default sorting, it removes all of the sorting, the styling, the search - everything - and becomes just black text in a column.

Where should I be putting it to prevent that? I want to sort by the ID column, #11.

<script>$(document).ready(function() {

    // Setup - add a text input to each footer cell
    $('#table_id tfoot th').each( function () {
        var title = $('#table_id thead th').eq( $(this).index() ).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );


    // DataTable
    var table = $('#table_id').DataTable(
{
        "bServerSide": true,
        "sAjaxSource": "***",
        "bProcessing": true,
    "iDisplayLength": 25,


});

    // 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();


            }
        } );


    } );
} );

</script>

Event Listeners not working for contents in Next Page

$
0
0

Hello there,
I've been developing a web application which displays database entries through DataTable. Within DataTable, I've got various user options/actions on each row, which are controlled by my Jquery event listeners. Upon testing these event listeners, they work correctly for the rows displayed initially on the first page. However, on the rows in next page, the event listeners don't work. Is there anyway that I can make my event listeners work throughout my entire DataTable? I've already tried calling DataTable from $(document).ready() and also after creating my HTML table, but none worked.

Thanks in advance!

Javascript button event not working on second page.

$
0
0

Hi!
I have buttons on all the rows that calls javasript event when clicked on.
Everything works perfectly as intented, but when i go to page 2 (im using paginate) the buttons no longer work.

I read something about preInit but im not sure that it is the right thing to do, if it i dont understand how.

How to remove a row before it is rendered

$
0
0

I would like to be able to remove certain rows from my table (based on a certain condition) inside the initialization but I'm not sure how to do it. I know I need to use the row().remove() method (w/ the draw()) in order to do it. I tried removing the row from within the createdRow callback but I'm not sure how to access the row object in order to call the API to remove the row. Here is an example of how I do the initialization (I trimmed some of it out for simplicity sake):

$('#table1').DataTable({
ajax:'reports/test1.txt',
deferRender:true,
fixedColumns:{leftColumns:2},
fixedHeader:true,
scrollX:true,
ordering:false,
'createdRow': function(row, data, dataIndex) {
    if (data.toString().indexOf('Total') > -1) {
      // add code to remove the row here
    }
}
});

I'm not sure how to reference the table object and then access the rows collection in order to remove the given row. I tried the following but that resulted in a "too much recursion" error from jQuery presumably because it's trying to self-reference itself and somehow created an infinite loop or I am referencing the wrong thing:

var myTable = $('#table1').DataTable({
ajax:'reports/test1.txt',
deferRender:true,
fixedColumns:{leftColumns:2},
fixedHeader:true,
scrollX:true,
ordering:false,
'createdRow': function(row, data, dataIndex) {
    if (data.toString().indexOf('Total') > -1) {
      myTable.rows($(row)).remove().draw();
    }
}
});

Thanks in advance for any help you can provide. I'd like to filter out the rows before they get rendered using the API. Right now I'm just using the jquery hide() method on the row but that doesn't properly update the paging and result count because I'm not currently going through the datatables API.

Viewing all 82201 articles
Browse latest View live


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