nhaberl nhaberl - 4 months ago 15
Javascript Question

How to find a specific row by values in jQuery datatables?

I would like to find a specific row by value within a datatables table out of a modal window.
I was looking on https://datatables.net/reference/type/row-selector but as I understand it's all based on selectors or internal IDs.
In my case I have 2 columns where I want to be able to lookup for the specific row to update the record after ajax request.

success: function (data) {
if (data.status_id > 0) {
alert(data.info);
} else {
alert(data.info);
}
contractsTable.row.add(dataJSON).draw(false);
}


EDIT

Here my code now - I've built my own unique rowid and used selector by id

Retrieving the data object

...
var d = datatable.row(this).data();
... set form values and so on


Save and Refresh datatable

$('#contractEditSave').on('click', function (e) {

dataJSON = {
id: $('#contractEditForm').data('contractid'),
member_id: $('#contractEditForm').data('memberid'),
member_name: $('#contractEditModalTitle').text(),
box_id: $('#contractBox').val(),
name: $('#contractName').val(),
description: $('#contractDescription').val(),
start: $('#contractStart').val(),
end: $('#contractEnd').val(),
amount: $('#contractAmount').val(),
unit: $('#contractUnit').val(),
max: 1
};

$.ajax({
type: 'POST',
url: '/save',
data: JSON.stringify(dataJSON),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
if (data.status_id == 0)
datatable.row('#' + dataJSON.id).data(dataJSON); //if update
...
} else {
datatable.row.add(dataJSON).draw(false); //if insert
...
}



$("#contractEditModal").modal('hide');

}
});
});

Answer

You can use fnFindCellRowIndexes to find row index holding certain data in given column.

Then you can use cell().data() API method to update the cell.

var table = $('#example').DataTable();

var rowId = $('#example').dataTable()
   .fnFindCellRowIndexes('Angelica Ramos', 0);

table
   .cell(rowId, 0)
   .data('Angelica Ramos (UPDATED)')
   .draw(false);

Please note that you need to include fnFindCellRowIndexes.js in addition to jQuery DataTables CSS/JS files.

See this jsFiddle for code and demonstration.