Matt Powell Matt Powell - 4 months ago 13
jQuery Question

jQuery Datatables plugin: How to specify row attributes when adding rows to table

I wondered if anyone else had come across this problem. When I originally build my table in my view, I'm using a custom attribute (call it

) in each table row to hold information I'll need to pass down for an ajax call. However, I'm also dynamically adding rows to the table, and I can't figure out how to pass back that same information (
) to be put in an attribute for the row. Currently, the only thing I'm doing when adding rows is building an array of arrays of strings that map exactly to my columns. This works fine, but there's no room to send back extra information.

I guess I don't need to store that in an attribute, if there's another way to send that information back to the view when adding rows. Does anyone have any ideas on this?



I was able to solve this problem by using the plugin's built-in functions to loop through the rows one by one. On the server, I created a private class that contained fields for all the information I need once I get back to the client. This includes actual values for the table cells, but also information to be placed in attributes. I create a list of these (one object = one row's worth of info), serialize them, and send them back to the calling ajax method. The following code assumes I've received the serialized string of objects back, and I'm in JS:

function(rowsToAdd) {

    var rowList = JSON.parse(rowsToAdd); // rows come back as object representations of table rows, with properties

    $.each(rowList, function(index, row) {
        var rowStringArray = [row.Prop1, row.Prop2, row.Prop3, row.Prop4];
        var rowPos = tableObject.fnAddData(rowStringArray); // add the row through the plugin, and receive the row's index in return
        var tableRowElement = tableObject.fnGetNodes(rowPos[0]); // get reference to <tr> element just added

        $(tableRowElement).attr('attributeINeeded', row.AttributeProp).attr('anotherAttributeINeeded', row.AttributeProp2);