How to search datatable using column name? - javascript

I am trying to search and filter data in datatable based on two columns.
Below is the code that I am using for search and redrawing the datatable.
(http://live.datatables.net/hapijuri/1/edit)
$(document).ready( function () {
var table = $('#example').DataTable({
"columns": [
{ title: 'title0', name: 'name0'},
{ title: 'title1', name: 'name1'},
{ title: 'title2', name: 'name2'},
{ title: 'title3', name: 'name3'},
{ title: 'title4', name: 'name4'},
{ title: 'title5', name: 'name5'},
]
});
table.column(1).search('Software Engineer')
.column(0).search('Bradley Greer').draw();
} );
The problem with this code is that it works on the column number (or index) and not on column name, however I have the column names on which I want to search.
Is there any way to search based on column name instead of index in datatables jquery?
Edit: Providing additional details to make sure I am able to present the question well.
So I have a datatable shown on UI and I am building a pivot table (using pivottable.js) in another tab using the datatable data.
On clicking the numbers in the pivot, I want the datatable data on the UI to be filtered so that it shows only those rows which are relevant to the number being clicked in pivot.
I am getting the column name and value corresponding to that number from pivot. I just need to search those column values in the datatable and show the filter the datatable accordingly.
As pointed in the example link that I shared, I am able to search through the data based on column index and the same is getting reflected on the UI.
What I am looking for is searching based on column name instead of column value.

For preventing a column being searched from table you have to add searchable:false. by default value of searchable & orderable is true.
var table = $('#example').DataTable({
"columns": [
{ title: 'title0', name: 'name0', "searchable": true},
{ title: 'title1', name: 'name1'},
{ title: 'title2', name: 'name2'},
{ title: 'title3', name: 'name3'},
{ title: 'title4', name: 'name4'},
{ title: 'title5', name: 'name5'},
]
});
no need to add below code unless you have server side data processing.
table.column(1).search('Software Engineer')
.column(0).search('Bradley Greer').draw();

Search a datatable using the column name
var table = $('#datatable-name').DataTable();
table.column('columnname:name').search("keyword").draw();

Related

Sorting a column display hidden rows in jqGrid

I have some rows I hide like that:
$("#"+rowid).hide();
My problem is that when the user clicks to sort a colmun, the hidden rows reappeared. There is a way to avoid this?
EDIT
I will try to explain a little bit more what I did with code example.
I start to create my grid with this params (and without datas).
var params = {
datatype: "local",
data: [],
caption: "Grid",
colNames:[ "Column A", "Column B" ],
colModel:[
{ name:"colA", key: true },
{ name:"colB" }
]
};
For some reasons, I reload next the grid with datas, like this:
$("#myGrid").jqGrid("clearGridData")
.jqGrid("setGridParam", { data: myDatas })
.trigger("reloadGrid");
And I have checkboxes with listeners, like this one:
$("#checkbox1").on("change", onCheckbox1Changed);
function onCheckbox1Changed() {
var rowid = ...;
var datas = $("#myGrid").jqGrid("getRowData");
for(var key in datas) {
if(datas[keys].colB === "" && $("#checkbox1").val() === true) {
$("#"+rowid).show();
} else if(datas[keys].colB === "" && $("#checkbox1").val() === false) {
$("#"+rowid).hide();
}
}
}
This code works like I want. Rows are hidden/shown depending on checkboxes. The problem is when I clik on a column to sort it, the hidden columns reappeared.
EDIT 2
I could force the grid to hide the rows after a sort. But I didn't find where I can find an event like "afterSort". There is "onSortCol" but it is called before the sort.
A solution will be to force that using "loadComplete". Like this:
var params = {
// ...
loadComplete: onLoadComplete
}
function onLoadComplete() {
onCheckbox1Changed();
}
I tried it and it works. But I am not very "fan" with this solution.
I find hiding some rows after displaying the page of data not the best choice. The main disadvantage is the number of rows which will be displayed. You can safe use $("#"+rowid).hide(); method inside of loadComplete only if you need to display one page of the data. Even in the case one can see some incorrect information. For example, one can use viewrecords: true option, which place the text like "View 1 - 10 of 12" on right part of the pager.
I personally would recommend you to filter the data. You need to add search: true option to the grid and specify postData.filters, which excludes some rows from displaying:
search: true,
postData: {
filters: {
groupOp: "AND",
rules: [
{ field: "colA", op: "ne", data: "rowid1" },
{ field: "colA", op: "ne", data: "rowid2" }
]
}
}
If you would upgrade from old jqGrid 4.6 to the current version (4.13.6) of free jqGrid, then you can use "ni" (NOT IN) operation:
search: true,
postData: {
filters: {
groupOp: "AND",
rules: [
{ op: "ni", field: "id", data: "rowid1,rowid2" }
]
}
}
In both cases jqGrid will first filter the local data based on the filter rules and then it will display the current page of data. As the result you will have the perfect results.
Sorting of such grid will not not change the filter.
Don't hide columns after the creation of the table, hide them directly when you create the grid using the option hidden, like this:
colNames: ['Id', ...],
colModel: [
{ key: true, hidden: true, name: 'Id', index: 'Id' },
....
]
If you want to hide columns on particular events after the creation of the grid, look at this article.
Hope it was you were looking for.

Javascript library for table rendering

I need to show an array of objects in the table like representation. Table has columns with the properties, and when clicked on the column it should show more data inside the table. It should be sortable.
Is there a JS library that could do this, so I dont have to write this from scratch?
Please see the attached image with the JSON object.
When the user clicks on Ana, additional row is inserted.
I created the demo https://jsfiddle.net/OlegKi/kc2537ty/1/ which demonstrates the usage of free jqGrid with subgrids. It displays the results like
after the user clicks on the "+" icon in the second line.
The corresponding code you can find below
var mydata = [
{ id: 10, name: "John", lname: "Smith", age: 31, loc: { location: "North America", city: "Seattle", country: "US" } },
{ id: 20, name: "Ana", lname: "Maria", age: 43, loc: { location: "Europe", city: "London", country: "UK" } }
];
$("#grid").jqGrid({
data: mydata,
colModel: [
{ name: "name", label: "Name" },
{ name: "lname", label: "Last name" },
{ name: "age", label: "Age", template: "integer", align: "center" }
],
cmTemplate: { align: "center", width: 150 },
sortname: "age",
iconSet: "fontAwesome",
subGrid: true,
subGridRowExpanded: function (subgridDivId, rowid) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
subgridData = [$(this).jqGrid("getLocalRow", rowid).loc];
$("#" + subgridDivId).append($subgrid);
$subgrid.jqGrid({
idPrefix: rowid + "_",
data: subgridData,
colModel: [
{ name: "location", label: "Localtion" },
{ name: "city", label: "City" },
{ name: "country", label: "Country" }
],
cmTemplate: { align: "center" },
iconSet: "fontAwesome",
autowidth: true
});
}
});
Small comments to the code. Free jqGrid saves all properties of input data in data parameter. I added id property to every item of input data. It's not mandatory, but it could be helpful if you would add more functionality to the grid. See the introduction for more details.
The columns are sortable based on the type of the data specified by sorttype property of colModel. To simplify usage some standard types of data free jqGrid provides some standard templates which are shortcurts for some set of settings. I used template: "integer" in the demo, but you could replace it to sorttype: "integer" if only sorting by integer functionality is important.
If the user click on "+" icon to expand the subgrid then jqGrid inserts new row and creates the div for the data part of the subgrid. You can replace subGridRowExpanded from above example to the following
subGridRowExpanded: function (subgridDivId) {
$("#" + subgridDivId).html("<em>simple subgrid data</em>");
}
to understand what I mean. The unique id of the div will be the first parameter of the callback. One can create any common HTML content in the subgrid. Thus one can create empty <table>, append it to the subgrid div and
then convert the table to the subgrid.
To access to the item of data, which corresponds to the expanding row one can use $(this).jqGrid("getLocalRow", rowid). The return data is the item of original data. It has loc property which we need. To be able to use the data as input for jqGrid we create array with the element. I's mostly all, what one have to know to understand how the above code works.
You can add call of .jqGrid("filterToolbar") to be able to filter the data or to add pager: true (or toppager: true, or both) to have the pager and to use rowNum: 5 to specify the number of rows in the page. In the way you can load relatively large set of data in the grid and the user can use local paging, sorting and filtering. See the demo which shows the performance of loading, sorting and filtering of the local grid with 4000 rows and another one with 40000 rows. All works pretty quickly if one uses local paging and not displays all the data at once.
I use datatables.net for all my "more complex than lists"-tables. I It's a very well kept library with loads of features and great flexibility.
In the "con" column I would say that it's so complex that it probably has quite a steep learning curve. Although the documentation is great so there is always hope for most problems.

Extjs 6 combobox values and display values not displaying correctly when setting values dynamically per row

Oof that was a long title.
In my current project I have a grid that holds a set of workshop records. For each of these workshops there is a set of rates that apply specifically to the given workshop.
My goal is to display a combobox for each row that shows the rates specific to that work shop.
I've got a prototype that works for the most part up on sencha fiddle, but there's something off about how the selection values are being created:
Ext.define('Rates',{
extend: 'Ext.data.Store',
storeId: 'rates',
fields: [
'rateArray'
],
data:[
{
workshop: 'test workshop 1',
rateArray: {
rate1: {show: "yes", rate: "105", description: "Standard Registration"},
rate3: {show: "Yes", rate: "125", description: "Non-Member Rate"},
rate4: {show: "yes", rate: "44", description: "Price for SK tester"}
}
},
{
workshop: 'test workshop 2',
rateArray: {
rate1: {show: "yes", rate: "10", description: "Standard Registration"},
rate2: {show: "yes", rate: "25", description: "Non-Member Registration"}
}
}
]
});
Ext.define('MyGrid',{
extend: 'Ext.grid.Panel',
title: 'test combo box with unique values per row',
renderTo: Ext.getBody(),
columns:[
{
xtype: 'gridcolumn',
text: 'Name',
dataIndex: 'workshop',
flex: 1
},
{
xtype: 'widgetcolumn',
text: 'Price',
width: 200,
widget:{
xtype: 'combo',
store: [
// ['test','worked']
]
},
onWidgetAttach: function (column, widget, record){
var selections = [];
Ext.Object.each(record.get('rateArray'), function (rate, value, obj){
var desc = Ext.String.format("${0}: {1}", value.rate, value.description);
// according to the docs section on combobox stores that use 2 dimensional arrays
// I would think pushing it this way would make the display value of the combobox
// the description and the value stored the rate.
selections.push([rate, desc]);
});
console.log(selections);
widget.getStore().add(selections);
}
}
]
});
Ext.application({
name : 'Fiddle',
launch : function() {
var store = Ext.create('Rates');
Ext.create('MyGrid',{store: store});
}
});
In the grid widget that I'm using for the combobox I'm using the onWidgetAttach method to inspect the current row's record, assemble the rate data from the record into 2 dimensional array, and then setting that to the widget's store.
When I look at the sencha docs section on using a 2 dimensional array as the store, it states:
For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo valueField, while the value at index 1 is assumed to be the combo displayField.
Given that, I would expect the combo box to show the assembled description (e.g.
"$150: Standard Registration") and use the object key as the actual stored value (e.g. "rate1").
What I'm actually seeing is that the display value is the rate and I'm not sure how sencha generates the combobox selections to see how the selection is being rendered out.
Is my assumption about how the 2-dimensionally array gets converted to the store wrong?
Well, your question is suffering from the XY problem. Because what you really want to do is the following:
You want to create a decent store for your combo, using a well-defined model with the meaningful column names you already have in "rateArray", then you define displayField and valueField accordingly, and in onWidgetAttach, just stuff the "rateArray" object into that store using setData.
Sth. along the lines of
xtype: 'widgetcolumn',
text: 'Price',
width: 200,
widget:{
xtype: 'combo',
store: Ext.create('Ext.data.Store',{
fields:['rate','description','show']
filters:[{property:'show',value:"yes"}]
}),
displayField:'description',
valueField:'rate',
onWidgetAttach: function (column, widget, record){
widget.getStore().setData(record.get("rateArray"));
}
},

Insert New Column To Kendo Datagrid

I Got Columns are quantity,Totalprice in my kendo grid. Then I want to add calculated column to my datagrid.
for example:
$("#gridcolumnadd").click(function (e) {
//1.add new column code Column Name is "Price For per kg"
//2.Set Column type is number
//3.Set Column aggregate is sum for footerTemplate
//4.add calculated values ex:(Totalprice/quantity) to "Price For per kg" with using for loop row count.
//redraw datagrid
});
Is possible to make it in kendo datagrid?
**
NOTE
I WANT TO CREATE DATAGRID FIRSTLY THEN ADD NEW COLUMN WITH ITS CALCULATION. THATS THE REASON "I WRITE JUST BUTTON CLICK"
**
For example; It is not working
var raw = grid.dataSource.data();
var length = raw.length;//if ı have many data . I can use For Loop
raw[0].new="Test"; //I think one data we have it
grid.columns.push({ field: "new" });
grid.dataSource.data(raw);
Some tips:
Instead of adding a column you should show and hide a column otherwise you will have to destroy current grid and create a new one (pretty expensive).
Have it created from the beginning. You might have fields in your model that are actually not coming from the server or you can have fields that are not in the model. You should decide.
Don't understand what do you mean by Set Column aggregate is sum for footerTemplate. As far as I understand you want to define an aggregate of a column so you should take a look into columns.aggregate.
Is this an editable grid? If not I do recommend to compute it when you receive the data from the server using either dataBound event handler or even using DataSource schema.parse
Lets see how this fits together...
This is my original schema:
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { type: "number" },
ProductName: { type : "text" },
UnitPrice: { type: "number" },
UnitsInStock: { type: "number" }
}
},
...
The first thing is add the Total which equals UnitPrice times UnitsInStock where I'm going to use parse.
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { type: "number" },
ProductName: { type : "text" },
UnitPrice: { type: "number" },
UnitsInStock: { type: "number" },
Total: { type: "total" }
}
},
parse : function (d) {
$.each(d, function(idx, elem) {
elem.Total = elem.UnitPrice * elem.UnitsInStock;
})
return d;
}
},
as you can see I've added an extra field Total and then in parse I iterate to compute the total for each record.
Next is define an aggregate that computes the total for all the data received.
aggregate: [
{ field: "Total", aggregate: "sum" }
]
This simple!
Now lets define the columns of my grid:
columns: [
{ field: "ProductName", title : "Name" },
{ field: "UnitPrice", title: "Price" },
{ field: "UnitsInStock", title:"Units" },
{
field: "Total",
title:"Total",
hidden: true,
aggregates: [ "sum" ],
footerTemplate: "#= sum #"
}
]
Here what is important is Total column where:
* I define as (initially) hidden using hidden: true.
* I also define an aggregate that is the sum.
* And finally I define a template for printing it.
Finally, I don't need to redraw the grid, it is enough invoking columnShow...
$("#gridcolumnadd").click(function (e) {
$("#grid").data("kendoGrid").columnShow(3);
});
All this together here : http://jsfiddle.net/OnaBai/63mg9/

ng-grid filter on full entity, not just column

This seems like a simple problem, but i can not find anything. All i want is to be able to search the full row entity, not just the columns i am showing. The ng-grid below, i can't find a way to search for anything in the "please" field and have it return.
My objects are really big, so i only show a few columns and then use the selected items to have a details view. Which i think is pretty standard.
var data = [
{key: 'key1', name: 'name1', please: 'search this'},
{key: 'key2', name: 'name2', please: 'search this please'},
];
$scope.grid = {
data: 'data',
columnDefs: [
{field: 'key'},
{field: 'name'}
]
};
The problem within ng-grid is this snippet
var searchEntireRow = function(condition, item, fieldMap){
var result;
for (var prop in item) {
if (item.hasOwnProperty(prop)) {
var c = fieldMap[prop.toLowerCase()];
if (!c) {
continue;
}
fieldMap is the columnDefs.
How can i leverage ng-grids cool searching for the full entity. Thanks for any help.

Categories