开发者

jQuery - datatables, how to get column id

How to g开发者_Go百科et a column id in datatable plugin for jquery I need column id for the update in database.


fnGetPosition

Get the array indexes of a particular cell from it's DOM element. Best used in combination with fnGetData().

Input parameters:

nNode : the node you want to find the position of. This my be either a 'TR' row or a 'TD' cell from the table. The return parameter depends on this input.

Return parameter:

int or array [ int, int, int ] : if the node is a table row (TR) then the return value will be an integer with the index of the row in the aoData object. If the node is a table cell (TD) then the return value will be an array with [ aoData index row, column index (discounting hidden rows),column index (including hidden rows) ].

Code example:

$(document).ready(function() {
    $('#example tbody td').click( function () {
        /* Get the position of the current data from the node */
        var aPos = oTable.fnGetPosition( this );

        /* Get the data array for this row */
        var aData = oTable.fnGetData( aPos[0] );

        /* Update the data array and return the value */
        aData[ aPos[1] ] = 'clicked';
        this.innerHTML = 'clicked';
    } );

    /* Init DataTables */
    oTable = $('#example').dataTable();
} );

From datatables.net


I think the stock answer above from datatables.net site was not helpful and didn't answer the question.

I believe neko_ime wants to get the column header value corresponding to the column of the selected item (since this is probably the same as the column name in the table, or the user has a mapping between the table header and the database table).

here is how you get the sTitle (column name value) for a given cell

(note I have my primary key in first column of every row, and have made sure that even if using movable columns with ColReorder that iFixedColumns is 1, to keep that key in the first column. my datatable is referenced by oTable. I am assuming that I have the cell DOM reference, which I call 'target' below):

var value = target.innerHTML;
var ret_arr = oTable.fnGetPosition( target );  // returns array of 3 indexes [ row, col_visible, col_all]
var row = ret_arr[0];
var col = ret_arr[1];
var data_row = oTable.fnGetData(row);
var primary_key = data_row[0];

var oSettings = oTable.fnSettings();  // you can find all sorts of goodies in the Settings
var col_id = oSettings.aoColumns[col].sTitle;  //for this code, we just want the sTitle

// you now have enough info to craft your SQL update query.  I'm outputting to alert box instead    
alert('update where id="'+primary_key+'" set column "'+col_id+'" ('+row+', '+col+') to "'+value+'"');

This is something I had to figure out myself, since i'm using JEditable to allow users to edit cells in the table.


The code snippet above actually helped me solve this issue for my particular situation. Here's my code:

// My DataTable
var oTable;

$(document).ready(function() {
    /*  You might need to set the sSwfPath! Something like:
    *   TableToolsInit.sSwfPath = "/media/swf/ZeroClipboard.swf";
    */
    TableToolsInit.sSwfPath = "../../Application/JqueryPlugIns/TableTools/swf/ZeroClipboard.swf";

    oTable = $('#tblFeatures').dataTable({
        // "sDom": '<"H"lfr>t<"F"ip>', // this is the standard setting for use with jQueryUi, no TableTool
        // "sDom": '<"H"lfrT>t<"F"ip>', // this adds TableTool in the center of the header
        "sDom": '<"H"lfr>t<"F"ip>T', // this adds TableTool after the footer
        // "sDom": '<"H"lfrT>t<"F"ip>T', // this adds TableTool in the center of the header and after the footer
        "oLanguage": { "sSearch": "Filter this data:" },
        "iDisplayLength": 25,
        "bJQueryUI": true,
        // "sPaginationType": "full_numbers",
        "aaSorting": [[0, "asc"]],
        "bProcessing": true,
        "bStateSave": true, // remembers table state via cookies
        "aoColumns": [
        /* CustomerId */{"bVisible": false },
        /* OrderId */{"bVisible": false },
        /* OrderDetailId */{"bVisible": false },
        /* StateId */{"bVisible": false },
        /* Product */null,
        /* Description */null,
        /* Rating */null,
        /* Price */null
        ]
    });

    // uncomment this if you want a fixed header
    // don't forget to reference the "FixedHeader.js" file.
    // new FixedHeader(oTable);
});

// Add a click handler to the rows - this could be used as a callback
// Most of this section of code is from the DataTables.net site
$('#tblFeatures tr').click(function() {
    if ($(this).hasClass('row_selected')) {
        $(this).removeClass('row_selected');
    }
    else {
        $(this).addClass('row_selected');

        // Call fnGetSelected function to get a list of selected rows
        // and pass that array into fnGetIdsOfSelectedRows function.
        fnGetIdsOfSelectedRows(fnGetSelected(oTable));
    }
});

function fnGetSelected(oTableLocal) {
    var aReturn = new Array();

    // fnGetNodes is a built in DataTable function
    // aTrs == array of table rows
    var aTrs = oTableLocal.fnGetNodes();

    // put all rows that have a class of 'row_selected' into
    // the returned array
    for (var i = 0; i < aTrs.length; i++) {
        if ($(aTrs[i]).hasClass('row_selected')) {
            aReturn.push(aTrs[i]);
        }
    }

    return aReturn;
}

// This code is purposefully verbose.
// This is the section of code that will get the values of
// hidden columns in a datatable
function fnGetIdsOfSelectedRows(oSelectedRows) {
    var aRowIndexes = new Array();
    var aRowData = new Array();
    var aReturn = new Array();
    var AllValues;

    aRowIndexes = oSelectedRows;    

    // The first 4 columns in my DataTable are id's and are hidden.
    // Column0 = CustomerId
    // Column1 = OrderId
    // Column2 = OrderDetailId
    // Column3 = StateId

    // Here I loop through the selected rows and create a
    // comma delimited array of id's that I will be sending
    // back to the server for processing.
    for(var i = 0; i < aRowIndexes.length; i++){
        // fnGetData is a built in function of the DataTable
        // I'm grabbing the data from rowindex "i"
        aRowData = oTable.fnGetData(aRowIndexes[i]);

        // I'm just concatenating the values and storing them
        // in an array for each selected row.
        AllValues = aRowData[0] + ',' + aRowData[1] + ',' + aRowData[2] + ',' + aRowData[3];
        alert(AllValues);
        aReturn.push(AllValues);
    }

    return aReturn;
}


Here an example of how to get an id after clicking on the row

$('#example tbody tr').live('click', function() {
         var row = example .fnGetData(this);
         id=row['id'];//or row[0] depend of situation
         function(id);
});

If you need all the id in a table you have to use a code like this:

$(exampleTable.fnGetNodes()).each(function() { 

    var aPos = exampleTable.fnGetPosition(this);
    var aData = exampleTable.fnGetData(aPos[0]);
    aData[aPos[0]] = this.cells[0].innerHTML; 

    IdSet.push(aData[aPos[0]]);
});

hope help!


A simple question like this deserves a good simple jQuery solution.

Assume your id is on row 0 and you want to access it when performing action on row 5 for example

$('td:eq(5)').click(function (){
    var id  = $(this).parent().find('td:eq(0)').html();
    alert('The id is ' + id);
});

Note this works for the filter and paged results as well.

I agree with @fbas the stock answer was not really helpful.


var oTable;

/* Get the rows which are currently selected */
function fnGetSelected(oTableLocal) {
    var aReturn = new Array();
    var aTrs = oTableLocal.fnGetNodes();

    for (var i = 0; i < aTrs.length; i++) {
        if ($(aTrs[i]).hasClass('row_selected')) {
            aReturn.push(aTrs[i]);
        }
    }
    // console.log( aReturn);
    return aReturn;
}

$(function() {

    /////////////////
    //btn_EditCustomer
    $('#btn_EditCustomer').on('click', function(e) {
        var anSelected = fnGetSelected(oTable);
        var rowData = oTable.fnGetData(anSelected[0]);
        console.log(rowData[0]);
    });
});  </script>


My solution was the following: have the primary key as the 1st column - this can be set as 'visible' or not. My edit and delete links are in the last but one and last columns in the row - they have css classes of 'edit' and 'delete' respectively. Then using rowCallBack, call a function like this:

<!-- datatables initialisation -->
"rowCallback": function( row, data ) {
    setCrudLinks(row, data);                  
}

function setCrudLinks(row, data) {
    d = $(row).find('a.delete');
    d.attr('href', d.attr('href')+'/'+data[0]);
    e = $(row).find('a.edit');
    e.attr('href', e.attr('href')+'/'+data[0]);
}

setCrudLinks() simply appends the primary key (data[0]) to the end of the links href (whatever that might need to be). This happens pre table render, and therefore works over pagination too.


I had the same use case and ended up spinning my code off into a datatables.net plugin. The repo is here: DataTables CellEdit Plugin

The basic initialization is quick and easy:

table.MakeCellsEditable({
    "onUpdate": myCallbackFunction
});

myCallbackFunction = function (updatedCell, updatedRow) {
    var columnIndex = cell.index().column;
    var columnHeader = $(table.column(columnIndex).header()).html();
    console.log("The header  is: " + columnHeader);
    console.log("The new value for the cell is: " + updatedCell.data());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜