Access specific line Datatable - javascript

I am defining a Datatable this way:
var dat_one = $('#dat_one').DataTable({
select: {
style: 'single'
},
responsive: true,
});
I would like to access a specific line of my datatable. I want to color a line that contains a specific string. (Example: Line that contains 'Ashton Cox' as column 1 and 'San Francisco' as column 3
I tried to color a selected line with this code :
$(".selected").css('background-color', '#ccffcc');
But doesn't works if my line is not selected.

Try using rowCallback. There you can change row attributes with value checking.
$('#example').dataTable( {
"rowCallback": function( row, data ) {
if ( data.grade == "A" ) {
$('td:eq(4)', row).html( '<b>A</b>' );
}
}
} );
This is documentation. Note the function has many other parameters you can use.
rowCallback( row, data, displayNum, displayIndex, dataIndex )

Following documentation, this is an alternative to Aruna Perera:
// var table = $('#dat_one').DataTable() ;
dat_one.rows().eq(0).each( function ( index ) {
var row = table.row( index );
var data = row.data();
var column0value = data[0];
if(column0value == "Airi Satou"){
$(row.node()).css("background-color", "yellow")
}
// ... do something with data(), or row.node(), etc
} );

Related

How to add hidden data to each row during creation in tabulator

I am building table with Tabulator5.2,
I need to pass some data to each row as hidden data like DB_ID ..etc
example:
{'extrId' : 10 , 'connectionDbIndex' : 101 }
In order to get the whole data when calling row.getData() or another method.
How i build the table:
This is the table headers:
var tableHeaders =
[
{formatter:"rowSelection", width:20 , titleFormatter:"rowSelection", hozAlign:"left", headerSort:false, cellClick:function(e, cell){cell.getRow().toggleSelect();}} ,
{title:'id", field:"ID" , hozAlign:"left" ,responsive:2 , headerFilter:'input', headerFilterLiveFilter:true ,headerSort:false }
]
This is table data:
var i = 0
counter = 2000
while (i < counter){
var more = {'DB_ID' : 2012 }
var row = {id:1+i, name:"Oli Bob"+i, progress:12, gender:"male"+i, rating:1, col:"red", dob:"19/02/1984", car:1 , site:'new' , ticket:12 , opened:false , cssClass:class2.randomId() , data : {'s' : 10}}
class2.insert_row(row , more)
i++
}
this is the function which responsible to add the rows:
insert_row(payload , more){
this.tableContent.push(payload)
this.rowMoreData.push(more)
for (let key in payload ){
var headerLabel = key
if (! this.alreadyColumsAdded.includes(headerLabel)){
this.alreadyColumsAdded.push(headerLabel)
var a = {title:headerLabel, field:headerLabel , hozAlign:"left" ,responsive:2 , headerFilter:'input', headerFilterLiveFilter:true ,headerSort:false }
this.tableHeaders.push(a)
}
}
}
Once all rows added to the dict. Finally build the table.
var table = new Tabulator(this.tableId, this.tableOptions);
How is it possible to add some hidden data to each row?
I do that too. I add visible to my column and set it to false.

Bootstrap datatables search input won't change

Im using bootstrap datatables, and im having a search input and whatever I do it won't remove Search text and add placeholder. I've seen examples here on stack and google but that didnt helped.
I believe this is the js for the search input:
function _fnFeatureHtmlFilter ( settings )
{
var classes = settings.oClasses;
var tableId = settings.sTableId;
var language = settings.oLanguage;
var previousSearch = settings.oPreviousSearch;
var features = settings.aanFeatures;
var input = '<input type="search" class="'+classes.sFilterInput+'"/>';
var str = language.sSearch;
str = str.match(/_INPUT_/) ?
str.replace('_INPUT_', input) :
str+input;
var filter = $('<div/>', {
'id': ! features.f ? tableId+'_filter' : null,
'class': classes.sFilter
} )
.append( $('<label/>' ).append( str ) );
var searchFn = function() {
/* Update all other filter input elements for the new display */
var n = features.f;
var val = !this.value ? "" : this.value; // mental IE8 fix :-(
/* Now do the filter */
if ( val != previousSearch.sSearch ) {
_fnFilterComplete( settings, {
"sSearch": val,
"bRegex": previousSearch.bRegex,
"bSmart": previousSearch.bSmart ,
"bCaseInsensitive": previousSearch.bCaseInsensitive
} );
// Need to redraw, without resorting
settings._iDisplayStart = 0;
_fnDraw( settings );
}
};
var jqFilter = $('input', filter)
.val( previousSearch.sSearch )
.attr( 'placeholder', language.sSearchPlaceholder )
.bind(
'keyup.DT search.DT input.DT paste.DT cut.DT',
_fnDataSource( settings ) === 'ssp' ?
_fnThrottle( searchFn, 400 ):
searchFn
)
.bind( 'keypress.DT', function(e) {
/* Prevent form submission */
if ( e.keyCode == 13 ) {
return false;
}
} )
.attr('aria-controls', tableId);
// Update the input elements whenever the table is filtered
$(settings.nTable).on( 'search.dt.DT', function ( ev, s ) {
if ( settings === s ) {
// IE9 throws an 'unknown error' if document.activeElement is used
// inside an iframe or frame...
try {
if ( jqFilter[0] !== document.activeElement ) {
jqFilter.val( previousSearch.sSearch );
}
}
catch ( e ) {}
}
} );
return filter[0];
}
As you know it datatables doesn't show in HTML, so its js.
How it looks, look at the search input
How I want it to look
you can use following code
oLanguage: {
"sSearch": ""
},
for Placeholder put the following code
$('.dataTables_filter input').attr("placeholder", "search...");

DataTable column filtering with dom-select column

I am using Jquery Datatable for my table and for filtering data I am following this example
DataTables > API > Multi-filter
This is working fine for regular columns. But I have some columns with drop downs as following.
For this column filtering is not working since it is considered the all entries of the drop down for filtering.
Can someone please suggest a way to put a filter for this king of column.
I am using DataTables version 1.10.7.
Thanks.
That was fun:
const table = $('#example').DataTable({
initComplete: function () {
this.api().columns().eq(0).each( function (index) {
const column = this.column(index);
const title = $(column.header()).text();
if(index === 2){
var select = $(`
<select class="form-control">
<option value="">Please choose</option>
</select>
`)
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
});
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
});
}else{
var input = $(`
<input class="form-control" type="text" placeholder="Search ${title}" />
`)
.appendTo( $(column.footer()).empty() )
.on( 'keyup change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column
.search( val )
.draw();
});
}
});
}
});
Working JSFiddle here.
After correction by Mr. Polywhirl (Thank you!) I revisited the problem and adapted a previous answer:
(function() {
$.fn.dataTable.ext.type.search.selected = (data) => !$(data).is("select")
? ''
: $(data).val();
$.fn.dataTable.ext.order['dom-select'] = function(settings, col) {
return this.api().column(col, {
order: 'index'
}).nodes().map(td => $('select', td).val());
}
})();
var table = $('#example').DataTable({
"columnDefs": [{
"orderDataType": "dom-select",
"type": "selected",
"targets": 2
}]
});
$("#example select").on("change", function() {
var $this = $(this),
val = $this.val(),
cellPosition = table.cell($this.parents("td")).index(),
rowDate = table.row(cellPosition.row).data();
$this.find("option").each((k, v) => ($(v).val() === val)
? $(v).attr("selected", "selected")
: $(v).removeAttr("selected"));
rowDate[cellPosition.column] = $this.prop("outerHTML");
table.row(cellPosition.row).data(rowDate);
table.cell(cellPosition).invalidate().draw();
});
Another working example here.
Hope that helps!
Found an answer from this question.
To write our own filtering function, we have to extend the $.fn.dataTable.ext.search function of Datatable.The function has 5 parameters and you need the fourth parameter (the original data source for the row). This fourth parameter is a JavaScript array, where the original HTML code of the given columns of the given rows can be found.
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex,original,counter ) {
var filterValue = $('#filterField').val();
var valueToFilter6 = original[6]; // this is the column with select box
if( valueToFilter6.indexOf('value="' + filterValue) != -1){
return true;
}
return false;
}
);
A complete working example fiddle can be found here.

SyntaxError: missing ) after formal parameters when adding if/else

Can anyone tell me what i am doing wrong , i want to have different views for different users in handsontable.I am defining the table as
document.addEventListener("DOMContentLoaded", function() {
var create_table = document.getElementById('create_table');
var mydata = document.getElementById('mydata').innerHTML;//to get the hidden element
var logged_user = document.getElementById('logged_user').innerHTML;// to get remote user
var plan_creator = document.getElementById('plan_creator').innerHTML;//to get the person who has created the plan
console.log(logged_user + " " + plan_creator);
console.log(mydata);
var searchResultCount=0;
var hot,searchFiled,resultCount;
function searchResultCounter(instance, row, col, value, result) {
Handsontable.plugins.Search.DEFAULT_CALLBACK.apply(this, arguments);
if (result) {
searchResultCount++;
}
}
var buttons = {
save:document.getElementById('save'),
load:document.getElementById('load'),
file:document.getElementById('file_export')
}
var objectData = JSON.parse(mydata);//to decode data in JSON format
console.log(objectData);
hot = new Handsontable(create_table, {
data:objectData,
colHeaders: true,
rowHeaders: true,
contextMenu: true,
minRows: 30,
minCols: 13,
maxCols:18,
maxRows:100,
copyPaste:true,
dropdownMenu: true,//plugin to display menu on column header
filters:true,
columnSorting:true,//plugin to enable sorting
sortIndicator:true,//to display sorting is done
comments:true,//to add comments
colHeaders:["Testcase Name","Cell Name","Customer","Flops","Title","Status","Mfix CCR","Scenerio Brief Description","Expected Results","CCR Status","CCR No","Remarks","Testcase Path"],
if(logged_user == plan_creator) {
columns:[//when using this not able to remove column
{data:'tc_name'},
{data:'cell_name'},
{data:'customer_name'},
{data:'flops' ,type:'numeric'},
{data:'title'},
{data:'status'},
{data:'mfix_ccr'},
{data:'test_scenerio'},
{data:'expected_results'},
{data:'ccr_status'},
{data:'ccr_num'},
{data:'remarks'},
{data:'tc_path'}],
}
else{
columns:[//when using this not able to remove column
{data:'tc_name' ,readOnly:true } ,
{data:'cell_name',readOnly:true },
{data:'customer_name',readOnly:true },
{data:'flops' ,type:'numeric',readOnly:true },
{data:'title',readOnly:true },
{data:'status',readOnly:true },
{data:'mfix_ccr',readOnly:true },
{data:'test_scenerio',readOnly:true },
{data:'expected_results',readOnly:true },
{data:'ccr_status',readOnly:true },
{data:'ccr_num',readOnly:true },
{data:'remarks'},//only remarks can be added by other user
{data:'tc_path',readOnly:true }],
}
search: {
callbak:searchResultCounter
}
});
searchFiled = document.getElementById('search_filed');
resultCount=document.getElementById('resultCount');
var exportPlugin=hot.getPlugin('exportFile');
Handsontable.dom.addEvent(searchFiled, 'keyup', function(event) {
var queryResult;
console.log(this.value);
searchResultCount = 0;
queryResult = hot.search.query(this.value);
console.log(queryResult);
//resultCount.innerText = searchResultCount.toString();
hot.render();
});
buttons.file.addEventListener('click', function() {// enabling the plugin to download the file
exportPlugin.downloadFile('csv', {filename: 'MyFile',columnHeaders:true});
});
I don't get any error when i remove the if/else statement and use only one scenerio .when using above code i am getting the error, but when i remove the if/else part and just use columns attribute in a simple way , i don't get this error.But i want to have different views for the creator of plan and others.
Is there any other way to do this?
Thanks
You can't use if statements when constructing an object, but you can use the ternary ?: operator, like this:
colHeaders: ... ,
columns: logged_user == plan_creator
? /* value in case they are equal */
: /* value in case they are not equal */,
search: ...
instead of using if else like
if(logged_user == plan_creator) {
columns:[//when using this not able to remove column
{data:'tc_name'},
{data:'cell_name'},
{data:'customer_name'},
{data:'flops' ,type:'numeric'},
{data:'title'},
{data:'status'},
{data:'mfix_ccr'},
{data:'test_scenerio'},
{data:'expected_results'},
{data:'ccr_status'},
{data:'ccr_num'},
{data:'remarks'},
{data:'tc_path'}],
}
else {}
you could use the ternary Operator:
columns: (logged_user === plan_creator)
? [//when using this not able to remove column
{data:'tc_name'},
...
]
: [//when using this not able to remove column
{data:'tc_name' ,readOnly:true },
...
]

Filtering an exact of string in DataTable JQuery

How do I search for an exact match in the search bar of JQuery Datable I tried using fnFilter but it's still not returning an exact match.
$(document).ready(function() {
var oTable = $('#datacal_table').DataTable({"order": [[4, "asc"]]});
oTable.fnFilter("^"+$(this).val()+"$", 4, true);
});
For example I only watch to search 'active' but what happens is the 'inactive' words also returns in the result. What should I do I need to be able to search only the the exact string.
EDIT
I tried one of inuka's links How to search for an exact string in a jQuery DataTable?
and it seems like my text class is interfering with the search, how do I get around this? I want to keep using my class text so that it's colored.
<td id="status">
<span class = "label {{ getStatusColor($data->status) }}"
id = "status_{{ $data->id }}">
{{ getStatusText($data->status) }}
</span>
</td>
when I only retain {{getStatusText}} the search works but when I try to class it, it doesn't.
<script type="text/javascript">
$(document).ready(function() {
var table = $('#datacal_table').DataTable({
"order": [[4, "asc"]]
});
$('.dataTables_filter input', table.table().container())
.off('.DT')
.on('keyup.DT cut.DT paste.DT input.DT search.DT', function(e) {
var term = $.trim(this.value);
if (term !== ""){
var termRegExp = new RegExp('^' + $.fn.dataTable.util.escapeRegex(term) + '$', 'i');
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex){
var isFound = false;
$.each(data, function (index, value) {
if (termRegExp.test(value)){ isFound = true; }
return !isFound;
});
return isFound;
}
);
}
table.draw();
if (term !== "") {
$.fn.dataTable.ext.search.pop();
}
});
});
</script>
The following answer from this post will give you an answer for searching term inside your HTML table structure.
$('#datacal_table').DataTable({
"columnDefs": [{
"targets": [4],
"render": function ( data, type, full, meta ) {
if(type === 'filter'){
return $('#datacal_table').DataTable().cell(meta.row, meta.col).nodes().to$().find('span').text();
} else {
return data;
}
}
}]
});
According to Datatables documentation this columnDefs.targets will give you the option to match only specified column name values. "targets": [4] will only focus on values under your Status column.
try this code
var oTable = $('.datatable').DataTable();
$('.dataTables_filter input').keyup( function () {
oTable.fnFilter("^"+$(this).val(),0,true,false);
});
working link http://codepen.io/subbu1191/pen/GmrvNd
1.{string}: String to filter the table on
2.{int|null}: Column to limit filtering to
3.{bool} [default=false]: Treat as regular expression or not
4.{bool} [default=true]: Perform smart filtering or not
5.{bool} [default=true]: Show the input global filter in it's input box(es)
6.{bool} [default=true]: Do case-insensitive matching (true) or not (false)
you have to make the smart filtering false in order to get the regex working

Categories

Resources