Prepopulate the text box for dataTables individual column searching - datatables

this should be easy but all the examples I can find are specific to the "general search" text box.
I'm trying to prepopulate an individual column search box, for example the "Name" field.
I don't need the code to do the search, just code to put a value in that "Search Name" text field.

There are 2 steps you can take to achieve this.
Step 1:
Use the searchCols option to set up your initial search terms. For example:
"searchCols": [
{ "search": "sat" }
]
This will cause column 1 to be filtered on the string sat.
If you want to use additional or different column filters, you can use null to skip columns - for example:
"searchCols": [
null,
{ "search": "foo" }
null,
{ "search": "bar" }
]
The above example will filter the 2nd and 4th columns.
Step 2:
You can take the existing code which creates the input fields in the table's footer cells, and modify that code to (a) use an index, and then (b) use the index to target the specific column(s) you want to pre-populate:
$('#example tfoot th').each(function ( idx ) {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
if ( idx === 0 ) {
$(this).find( 'input' ).val( 'sat' );
}
});
In the above fragment, I took the code linked to in the question and added the idx variable, and then used that to target the first input field, and populate it with "sat".
Without step 2, the DataTable will not show you the values being used to perform filtering.

initComplete: function () {
this.api().columns().every( function () {
var column = this;
if ($(column.header()).hasClass('datatable_search')) {
var that = this;
//player var taken from url
if (column.header().innerText.includes('Players') && players.length){
//prepopulate the input field
$( 'input', this.header() ).val(players)
//use the url.players arg in the search and redraw
this.search( players ).draw();
}
$( 'input', this.header() ).on( 'keyup change clear', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );

Related

In ag grid drop down, how to show name once selected and on save set value instead of name.?

Using this reference, I had worked ag grid drop down.
Issue : once I selected a drop down value, then getvalue() returns value instead of name. Hence it shows the number on the column and it should be text.
If I change that to name, while saving, its bind to name . But here it should be value.
Required : getValue should return name & saving the array should contain value.
agInit(params: any): void {
this.params = params;
this.value = this.params.value;
this.name = this.params.name;
this.options = params.options;
}
getValue(): any {
return this.value;
}
ngAfterViewInit() {
window.setTimeout(() => {
this.input.element.nativeElement.focus();
})
}
stackbltiz here
here
How can I achieve this.
You don't have to create new cellRenderer and cellEditor for it, ag-grid provides inbuilt select for it. **
When you using objects (for dropdown\combobox) inside single cell - you have to implement value handlers: valueParser and valueFormatter:
Value parser: After editing cells in the grid you have the opportunity to parse the value before inserting it into your data. This is done using Value Parsers.
colDef.valueParser = (params) => {
return this.lookupKey(mapping, params.newValue);
}
Value formatter: Value formatters allow you to format values for display. This is useful when data is one type (e.g. numeric) but needs to be converted for human reading (e.g. putting in currency symbols and number formatting).
colDef.valueFormatter = (params) => {
return this.lookupValue(mapping, params.newValue);
}
*where mapping represents your object and inside each of those functions you are just extracting key or value.
Original solution:
lookupValue(mappings, key) {
return mappings[key];
}
lookupKey(mappings, name) {
var keys = Object.keys(mappings);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (mappings[key] === name) {
return key;
}
}
}
and here my little bit modified:
lookupValue(mappings, key:string) {
if(!mappings || !mappings.find(item => item.Id == key)) return null;
else
return mappings.find(item => item.Id == key).Value;
}
lookupKey(mappings, name) {
let key: any;
for (key in mappings) {
if (mappings.hasOwnProperty(key)) {
if (name === mappings[key]) {
return key.Id;
}
}
}
}
UPDATE
To populate dropdown you need yo use cellEditorParams:
colDef.cellEditor = 'selectCellEditor';
colDef.cellEditorParams = {
values: yourList,
},
** But in case when it could be required you still need to have both of renderers and store object inside, and then you would be able to choose what would be displayed on every stage.

VueJS disable sorting when user enters data

I have data list which I have bind to input elements in table. When table header are clicked the data list is sorted in asc or desc. Now the problem is e.g.: when user has sort "Name" column in desc and he wants to change first row name to "Dave" from "Jet Li" as soon as he type "D" the list get sorts. What can I implement to have the sorting wait for the user to type and once he finishes he can then again click the headers and sort the data.
Issue gif : Check issue here
My fiddler example : https://jsfiddle.net/bngp6oas/1/
filteredData: function () {
var sortKey = this.sortKey
var filterKey = this.filterKey && this.filterKey.toLowerCase()
var order = this.sortOrders[sortKey] || 1
var data = this.data
if (filterKey) {
data = data.filter(function (row) {
return Object.keys(row).some(function (key) {
return String(row[key]).toLowerCase().indexOf(filterKey) > -1
})
})
}
if (sortKey) {
data = data.slice().sort(function (a, b) {
a = a[sortKey]
b = b[sortKey]
return (a === b ? 0 : a > b ? 1 : -1) * order
})
}
return data
}
}
You could use the .lazy model modifier to only update the value (and therefore the sorting) after the input looses focus.
In your code from the fiddle that would look like:
<input type="text" v-model.lazy="entry[key]" />
See the Vue documentation here: https://v2.vuejs.org/v2/guide/forms.html#lazy
You can make use of the .lazy modifier.
In order to work properly, you will also need to add a unique key to each row.
Updated grid data with keys:
gridData: [
{ id: 1234 , name: 'Chuck Norris', power: Infinity },
{ id: 2345, name: 'Bruce Lee', power: 9000 },
{ id: 3456, name: 'Jackie Chan', power: 7000 },
{ id: 4567, name: 'Jet Li', power: 8000 }
]
See updated fiddle here

Change AG grid previous cellStyle dynamically based on condition of other nodes or row value

I can able to change current cellStyle based on some condition of current node. But I have to change the immediate previous cellStyle based on some condition in current node.
columnDefs = [
{ headerName: "TripStatus", field: "TripStatusCode",cellStyle: this.cellStyling},
]
Call following method to change the style dynamically
cellStyling(params:any){
// This will change the current cell style only. But I need to change the style of immediate previous cell style.
if(params.node.TripStatusCode==='CO')
return {'background-color': 'red'};
}
Check out cellClassRules
cellClassRules = {
'your-css-class': params => {
if (params.colDef.field === "myCurrentField" &&
params.data["previousField"] === "value") {
return true;
} else {
return false;
}
},
'your-other-css-class': params => {return false}
}
You can define as many class rules as you need, just separate by comma and the function should return true/false.

Datatables mDataProp: val param undefined

I'm working on implementing a custom filter value where existing html tags are stripped away for each applicable table column values.
(The reason is that filtering the data also accounts for values inside the html tags, and this is not desired.)
This is a legacy code base, using datatables v1.9.0.
The table is constructed using params, such as aoColumns, aaData.
For table data is using array of arrays: i.e:
aaData = [
['12450','<a href='javascript:doStuff(123, 456)>value2</a>', 'User 1', '$500'],
['12455','...','...','...'],
['12462','...','...','...'],
['12314','...','...','...'],
[...],
...
]
Table has to use mDataProp for applicable aTargets
The function signature is:
tableOptions["aoColumnDefs"] = [
{
"mDataProp": function (source, type, val) {
console.log("source ", val); // This returns: row array
console.log("type ", type); // This returns each type (except for 'set')
console.log("val ", val); // This returns: undefined
var obj = {};
var temp = angular.element('div');
temp.innerHTML = val;
if (type === 'set') {
obj.value = val;
obj.value_filter = temp.textContent || temp.innerText;
console.log(obj.value_filter);
return;
} else if (type === 'filter') {
return val;
} else if (type === 'sort') {
return val;
}
return obj.value;
},
"sDefaultContent": '',
"aTargets": [ 1 ]
},
]
The issue is that val parameter inside mDataProp always returns undefined, so the table data population would error out, if not for the sDefaultContent property.
See this fiddle.
Why cannot the mDataProp get the val parameter populated? Does mDataProp support an array of arrays as data source? (The documentation is not clear about this)
After digging through a bit I found out that when mDataProp is used as a function, it does not have any reference to the data being passed to the datatable from the javascript array variable, thus returning undefined for val.
The workaround for this particular case is to use direct array position references in the source parameter, depending on the aTargets value to be used. (If using "aTargets": [ 1 ], then have to call source[1] in the mDataProp function).
I did not use if (type === "set"){}, 'cause I could not access it.
"mDataProp": function(source, type, val) {
var obj = {};
obj.value = source[1]; // Set column value
// Process value as desired ...
obj.value_filter = obj.value + ' foobar';
// Return value for filtering
if (type === 'filter') {
return obj.value_filter;
}
// Return original value for display, sort, etc.
return obj.value;
}
Click updated fiddle.

How to set cell value in DataTable on button click

I'm trying to modify a cell value using DataTable (the new version) when an outside button is clicked.
I have the following for now:
$(document).on('click', '.dropdown-menu li a', function () {
if ($(this).text() == "development") {
var cell = table.row( 6 ).data()[4]
cell.data( "development" ).draw();
}
});
This doesn't work since I think the table row and data retrieval method doesn't return an object with .data() attribute that allows me to set data cell value. I'm getting the following error: cell.data is not a function. (In 'cell.data( "development" )', 'cell.data' is undefined)However, I'm not sure how to access a table cell value the .data() way without having a click even in the table. My button is placed outside the table somewhere else.
Any idea how to make this work?
Since DataTables 1.10+ might not support fnGetNodes() as mentioned on the API landing page itself, instead now you can use rows().nodes().
Example: http://jsfiddle.net/cmedina/7kfmyw6x/28/
var table = $('#example').DataTable({sorting : false});
var row = table.row(0).node();
$('#test').on( 'click', function () {
var text = "development";
if (text == "development") {
table.cell(row, 0).data('Development').draw();
}
});
If you work with DataTables < 1.10 then you can use fnUpdate
Example: http://jsfiddle.net/cmedina/7kfmyw6x/29/
var oTable = $('#example').dataTable({sorting:false});
$('#test').on( 'click', function () {
var text = "development";
if (text == "development") {
oTable.fnUpdate('Development', 0, 0 ); // Single cell
}
})
you can use fnUpdate Datatables Function to update any specific cells just by row and col indexes.
something like this :
var oTable = $('#example').dataTable();
$('#button').click(function() {
var row = document.getElementById("indexDepRow").value;
var col = document.getElementById("indexDepCol").value;
oTable.fnUpdate('development', parseInt(row), parseInt(col));
});
See JsFiddle EXAMPLE