I'm currently using the DataTables plugin for my project.
I have an AJAX sourced datatable where you can only ever have one row selected, now because my datatable is done server-side I need to keep track of which one is selected when changing pages.
Therefore I have been using this solution but this only seems to work for multiple row selection
Now essentially what I want to happen is, when you select a new row it should add the new row id to the array but also remove the previously added row id from the array, so there should only ever be one result in the array at a time.
Visually for better understanding:
var selected = []
Click Row 1 after loading table = [row_1]
Click Row 2 removing row_1 and adding row_2 = [row_2]
var selected = [];
$("#example").DataTable({
"processing": true,
"serverSide": true,
"ajax": "scripts/ids-arrays.php",
"rowCallback": function( row, data ) {
if ( $.inArray(data.DT_RowId, selected) !== -1 ) {
$(row).addClass('selected');
}
}
});
$('#example tbody').on('click', 'tr', function () {
var id = this.id;
var index = $.inArray(id, selected);
if ( index === -1 ) {
selected.push( id );
} else {
selected.splice( index, 1 );
}
$(this).toggleClass('selected');
} );
Instead of adding an element to the array, you could replace the whole array. It seems a bit wasteful to use an array to store a single element, but there you go.
selected.push( id );
becomes
selected = [id];
I have a table in which I can edit and modify each cell.
I would like to highlight the cell that I modified.
At the moment I can only highlight the entire row but I don't have what I want to do.
I use createdRow to make the cells editable and get the modified row.
How can I do to highlight that modified cell?
var table = $("#deploymentMap_table").DataTable({
data: constructRaws(dataSet),//tbody
paging: false,
searching: false,
info: false,
fixedHeader: true,
scrollY: false,
scrollX: false,
responsive: false,
dom: 't', //display only the table
order: [[ 0, 'asc' ]],//order by 'service' col
columnDefs:[
{
targets:'_all',
render:function(data){
if(data == null) {return ""
} else {return data;}
}
},
{ targets: [0,1], "width" : "200px"},
],
columns: constructColumns(dataSet),//thead
dom: 'Bfrtip',
// attribute classname (background color) for services
rowCallback: function(row, data, index){
if ( data.code == 1 ) {
$('td', row).each( function ( value, index ) {
if($(this).contents().first().text()){
$(this).addClass('td_colorCD');
}
} );
}
$(row).find('td:eq(0)').css('background-color', '#7f7f7f').css('color', '#fff').css('text-align', 'left');
$(row).find('td:eq(1)').css('background-color', '#7f7f7f').css('color', '#fff').css('text-align', 'left');
$.each(row.childNodes, function(i,value){
if(value.innerText == "NoUP"){
$(value).addClass('td_colorBSF');
}
else if(value.innerText){
$(value).addClass('td_color');
}
})
},
// Make all cell editable
createdRow: function(row, data, dataIndex, cells) {
console.log(cells);
let original
row.setAttribute('contenteditable', true)
row.setAttribute('spellcheck', false)
row.addEventListener('focus', function(e) {
original = e.target.textContent
})
row.addEventListener('blur', function(e) {
if (original !== e.target.textContent) {
$('td', row).removeClass();
$('td', row).addClass('td_color_change');
const r = table.row(e.target.parentElement)
r.invalidate();
var lign = e.target.innerText;
lign = lign.split('\t');
var nRow = $('#deploymentMap_table thead tr')[0].innerText;
head = nRow.split('\n\t\n');
var newAR = mergeArrayObjects(head, lign);
console.log("newAR", newAR);
$(dataSet).each(function( index, values ) {
if(newAR.service[0].Services == values.service_name){
delete values.regions;
values.regions = newAR.region;
console.log(values);
}
})
console.log("dataset", dataSet);
}
})
}
});
I think the easiest way to handle this is to replace your rowCallback with a DataTables delegated event.
Below is a simple example which would change the color of a specific cell when you leave that cell:
Step 1) The onblur event requires the cell to have a tabindex attribute. You can add this however you wish - but here is one way, in your existing code:
$.each(row.childNodes, function(i,value){
$(value).attr('tabindex', i); // this line is new
// your existing code goes here
})
Note - this could be improved as it repeats tab indexes across rows. But it illustrates the approach.
Step 2: Add a new onblur event listener, after the end of your DataTable definition:
$('#deploymentMap_table td').on('blur', function () {
this.classList.remove("td_color");
this.classList.add("td_color_change");
} );
Step 3: The above code would need to be enhanced to include your edit-checking logic, which checks for an actual cell value change.
You can get the "before" cell values using this:
table.cell( this ).data();
And the "after" cell values using this - which gets the value from the HTML table (the DOM node), not from DataTables:
table.cell( this ).node().textContent;
The updated listener would be something like this:
$('#deploymentMap_table td').on('blur', function () {
var cellValueStart = table.cell( this ).data();
var cellValueEnd = table.cell( this ).node().textContent;
//console.log( cellValueStart );
//console.log( cellValueEnd );
if (cellValueEnd !== cellValueStart) {
table.cell( this ).data(cellValueEnd);
this.classList.remove("td_color");
this.classList.add("td_color_change");
}
} );
The table.cell( this ).data(cellValueEnd) command updates the cell in DataTables so that it matches the value you typed into the HTML cell. If you do not do this, then the data in the DataTables object (behind the scenes) will be out-of-sync with the data in the HTML table (what you see on your screen).
Warning: This approach is basic. It does not cover the case where a user may do the following:
Edit a cell from "A" to "B".
Leave the cell, so it is highlighted.
Return to the cell and edit it back from "B" to "A".
Leave the cell again.
In this case, the cell will remain highlighted.
One way around this is to capture the original state of every cell when you first load the table - and then check each edit against the value in the original data. This can be done, if needed - but is outside the scope of this question. But it also depends on what you need to do with the data, after you have finished editing it. If this is important to you, then it may be worth asking a new question for that specific problem.
I've got two datatables and there is a dropdown created in the second one with data from the first. I've created a jsbin here
If you add a couple of instructions to the first table (add any text and then click Add Instruction) - then click on the Load Copied Data button, you will see the dropdown box is populated from the first table.
If I do:
$('#btnTest').on('click', function (e) {
var tsor = $('#tblSORSInstall').dataTable();
var ins = tsor.fnGetData();
alert(ins);
});
It basically gives me the html for the dropdown - how do I get which value they have chosen? I was thinking of having a hidden column and updating that on the onchange of the dropdown, but is there a better way?
Thanks in advance
You may use jQuery.map() to generate an array of selected text/value, like below.
$('#btnTest').on('click', function (e) {
//var tsor = $('#tblSORSInstall').dataTable();
var ins = $('#tblSORSInstall').find("tbody select").map(function() {
return $(this).find(":selected").text() // get selected text
//return $(this).val() // get selected value
}).get()
alert ( JSON.stringify(ins, null, 2) )
});
Here is your JS Bin - updated
Using tsor.fnGetNodes() you can get all table row nodes, then you can loop through those and get the select values.
Final code will look something like
$('#btnTest').on('click', function (e) {
var tsor = $('#tblSORSInstall').dataTable();
var ins = tsor.fnGetData();
var a = tsor.fnGetNodes();
$.each(tsor.fnGetNodes(), function (index, value) {
alert($(value).find('select').val());
});
});
In the example below highlighting works quite well with individual rows.
In my code I can see that selection of an individual row works, however, the actual highlighting does not work.
I am using Twitter Bootstrap 3 + Datatables.
http://datatables.net/release-datatables/examples/api/select_single_row.html
Any help would be appreciated. I have followed the example as is and I think perhaps I have not configured the table properly in its init or Bootstrap does not quite like highlighting.
var oTable;
$( document ).ready(function() {
/* Add a click handler to the rows - this could be used as a callback */
$("#pTable tbody tr").click( function( e ) {
if ( $(this).hasClass('row_selected') ) {
$(this).removeClass('row_selected');
}
else {
oTable.$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
}
});
/* Add a click handler for the delete row */
$('#deletePButton').click( function() {
var anSelected = fnGetSelected( oTable );
if ( anSelected.length !== 0 ) {
oTable.fnDeleteRow( anSelected[0] );
}
});
/* Init the table */
oTable = $('#pTable').dataTable( );
/* Get the rows which are currently selected */
function fnGetSelected( oTableLocal )
{
return oTableLocal.$('tr.row_selected');
}
});
So the deleteButton which is being referenced in the code works if I select a row and delete a row.
Just the highlighting doesnt work!
Is your table id "#pTable"?
Did you try adding a debbug stop on that method, to be sure that the selector is working?
On bootstrap to hightlight a row you must use one of this classes
Class Description
.active Applies the hover color to a particular row or cell
.success Indicates a successful or positive action
.warning Indicates a warning that might need attention
.danger Indicates a dangerous or potentially negative action
Bootstrap 3 Tables
I'm new to JS. How can i highlight selected row when user clicked on it at editable datatable?
Thank you.
If you are using the jquery datatable plugin, there is an example here :
http://datatables.net/release-datatables/examples/api/select_row.html
$(document).ready(function() {
/* Add/remove class to a row when clicked on */
$('#example tr').click( function() {
$(this).toggleClass('row_selected');
} );
/* Init the table */
var oTable = $('#example').dataTable( );
} );
/*
* I don't actually use this here, but it is provided as it might be useful and demonstrates
* getting the TR nodes from DataTables
*/
function fnGetSelected( oTableLocal )
{
return oTableLocal.$('tr.row_selected');
}