Dynamically change datatables column width via API - javascript

I know we can set the columns width on a datatable via the columns.width option. But now I want to change that option on the xhr event.
Based on the ajax response I get from the server I want to hide/show a column and adjust the other columns width accordingly (they are all fixed size). Is there any way to achieve that via API?
I looked around all docs but seems it's not possible to achieve.

You cannot change settings once the dataTable is initalised. But if you are using column.width and you have turned autoWidth off, then the width of each column is easy to change. Here is an example :
var table = $('#example').DataTable({
autoWidth: false,
ajax: {
url: 'https://api.myjson.com/bins/avxod'
},
columns: [
{ data: 'name', width: 50 },
{ data: 'position', width: 50 },
{ data: 'salary', width: 50 },
{ data: 'office', width: 50}
]
})
$('#example').on('xhr.dt', function() {
$('#example thead th:eq(1)').width('400');
})
demo -> http://jsfiddle.net/cc7x6h64/
It works because column.width is injected into each <th> as style="width: xxx;"

Related

Style AG Grid's rowGroup

I am currently using AG GRID in my project and have implemented the RowGroup functionality for one of the columns,
Here's my code:
HTML
<div id="myGrid" style="height: 400px;width:80%; display:none" class="ag-theme-alpine">
</div>
JS:
var gridOptions_PortCd = {
suppressClickEdit: true,
columnDefs: [
{ headerName: "Col1", field: "Col1", rowGroup: true, hide: true },
{ headerName: "Val1", field: "val2", minWidth: 200 },
],
defaultColDef: {
sortable: true,
filter: true,
resizable: true,
},
autoGroupColumnDef: {
headerName: 'ColA',
minWidth: 200,
},
groupDisplayType: 'singleColumn',
animateRows: true,
};
I'm able to feed the grid some JSON data, and all looks great (I'm not including the rest of the code as I do not think it is relevant to the question).
Now what's happening is, the Grid looks totally great, however I want to be able to style to rowGroup row in my grid because it is dark and I'd want it to just to be plain white.
here's what mine looks like:
mygrid
Sorry for the link only (SO won't let me paste image).
In essence, how do I set the COLOR of the ROW GROUP to something different, I've tried things like:
.ag-theme-alpine .ag-row.ag-row-level-0 {
background-color: #dddbdb!important;
}
but that doesn't work. I'm not sure why it shows up as navy blue rather than just plain white or grey or something, but my hopes are to change it. Any pointers?
Goal is for it to look like this (In AG GRID website example)
Example
I've looked on AG GRID website's documenation but they do not provide info as how to style it.
EDIT: I changed it like so, and now it looks like this:
.ag-cell {
background-color: yellow !important;
}
updated
If you want to chage the color of cells in RowGroup,try to use:
.ag-cell {
background-color: #dddbdb !important;
}
result:
Update:
Try to change the background color of ag-cell-wrapper:
.ag-cell-wrapper {
background-color: #dddbdb !important;
}
result:

Updating Columns Dynamically - Alloy UI

I'm trying to change columns dynamically in my Alloy UI DataTable - depending on what button is selected, columns are changed depending on which data is returned.
My columns get updated, however the actual data is never included in the table. When I don't define any columns both the columns and data are returned - I of course want control of how my columns are displayed and want to set their attributes
Below is my code:
var dataTable = new Y.DataTable({ //Defining Datatable with no columns preset
editEvent: 'dblclick',
plugins: [{
cfg: {
highlightRange: false
}]
});
button.on(
'click', //On Click...
function() {
var category = $(this).attr("id"); //value retrieved from id of button selected
dataSource = new Y.DataSource.IO({source: '/searchMyData
dataSource.sendRequest({
dataType: 'json',
on: {
success: function(e) {
response = e.data.responseText;
setColumnNames(category); //Set the Columns...
data = Y.JSON.parse(response);
dataTable.set('data', data);//Then the Data
dataTable.render('#my-container');
},
failure: function() {
alert(e.error.message);
}
}
});
function setColumnNames(tabName){ //Defining Columns
var columns1 = [
{ key: 'id', label: 'ID', width: '70px' },
{ key: 'name', label: 'Name', width: '70px' }
];
var columns2 = [
{ key: 'id', label: 'ID', width: '70px' },
{ key: 'addr', label: 'Address', width: '70px' }
];
switch (category) {
case "person":
dataTable.set('columns', columns1);
break;
case "address":
dataTable.set('columns', columns2);
break;
default:
console.log('');
}
There's no issue with the data returning from the ajax request, only when it comes to loading it to the table with a new set of columns defined. I've tried the reset() method on both columns and data on each click, but no luck.
It turns out the keys returned from my request were being capitalized and included underscores (just how they're defined in the database) - I've also noticed defining the columns key is case sensitive. If I changed a single character from lower case to upper than the column would not display data.

Handsontable is showing all columns, virtual rendering is working only for rows

I've got the last version of handsontable and now they are showing all my columns on the screen, for ex: I have 1000 cols and 1000 rows and table is showing 10 rows for my width and 1000 cols.
var hot = new Handsontable(el, {
colWidths:30,
colHeaders: true,
data: data,
minSpareRows: 1,
stretchH: "all",
variableRowHeights: false,
height: 200,
width: 200,
})
The latest version fixed this. Check this link.

dataTable prevent column resizing when filtering data

I have a dataTable which I am filtering dynamically once the table has been initialized. I have a JS function that takes 1 arg which is the string to be used as the filter. I'm setting the filter on the table using...
oTable = fnFilter(strFilter);
This works fine, but after the table is filtered the columns seem to re-size themselves.
I already have bAutoWidth set to false, so I'm not sure what else I can apply that will prevent the columns from resizing. I want the sizes I have defined in the th tags to remain no matter what data is present.
bAutoWidth is just a flag indicating whether dataTables should calculate the widths automatically. Setting it to false is an optimisation feature, see the docs :
Enable or disable automatic column width calculation. This can be
disabled as an optimisation (it takes some time to calculate the
widths) if the tables widths are passed in using aoColumns.
But the browser will still expand / shrink the <td>'s according to their content. This is how tables work. To achieve what you want, the trick is to use sScrollX and aoColumns like this :
var dataTable = $('#example').dataTable({
sScrollX: "100%",
aoColumns: [
{ "sWidth": "50px" },
{ "sWidth": "50px" },
{ "sWidth": "50px" },
{ "sWidth": "50px" },
{ "sWidth": "50px" }
]
});
This gives a table with the width of 250px, each column 50px - regardless of the content. sScrollX forces dataTable to maintain the width both of the table and the columns.
See this fiddle -> http://jsfiddle.net/MW8Ku/ demonstrating that the above apporach also is working after a call to fnFilter.
The answer referring to sScrollX and sWidth is using legacy DataTables API. Since v 1.10+, the syntax is:
$('#example').dataTable( {
"scrollX": true,
"columns": [
{ "width": "50px" },
{ "width": "50px" },
{ "width": "50px" },
{ "width": "50px" },
{ "width": "50px" }
]
});
Ref:
scrollx
columns

JQGrid reduce the no of columns on window resize event

I'm having a problem with jqGrid. I have a table with many columns. When I change the window or If open the web app in a mobile device, It should show only 4 or 5 columns in the grid table instead of many columns or else It should allow scrolling within the grid. So how to reduce the number of columns in the JQGrid on the window resize event?.
I have tried like following and the resize event is working fine but look&feel is not good due to more columns in the grid and no scroll bar.
My Html,
<table id="list2"></table>
My jqGrid code,
$("#list2").jqGrid({
url: '/Project/GridData',
datatype: "json",
mtype: 'POST',
colNames: ['edit', 'view','id','Project_Name','Project_Name2','Project_Nam3','Project_Number','Project_Manager', 'Business_Unit', 'Project_Admin_Name', 'Remarks', 'Is_Active', 'Created_Date','Modified_Date'],
colModel: [
{ name: 'edit', index: 'edit', width: 55 },
{ name: 'view', index: 'view', width: 55 },
{ name: 'id', index: 'id', width: 55, hidden: true },
{ name: 'Project_Name', index: 'Project_Name', width: 140 },
{ name: 'Project_Name2', index: 'Project_Name2', width: 140 },
{ name: 'Project_Name3', index: 'Project_Name3', width: 140 },
{ name: 'Project_Number', index: 'Project_Number', width: 140 },
{ name: 'Project_Manager', index: 'Project_Manager', width: 140 },
{ name: 'Business_Unit', index: 'Business_Unit', width: 140 },
{ name: 'Project_Admin_Name', index: 'Project_Admin_Name', width: 140, align: "right" },
{ name: 'Remarks', index: 'Remarks', width: 180, align: "right" },
{ name: 'Is_Active', index: 'Is_Active', width: 100, align: "right" },
{ name: 'Created_Date', index: 'Created_Date', width: 150, sortable: false },
{ name: 'Modified_Date', index: 'Modified_Date', width: 150, sortable: false }
],
rowNum: 10,
rowList: [10, 20, 30,50,100,500,1000],
//pager: '#pager2',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
loadonce: true,
ignoreCase: true,
viewrecords: true,
pagepos: 'left',
forceFit: true,
shrinkToFit: false, // to enable the scroll bar in the responsive mode
height: 500,
width:1600,
altRows:true,
altclass:'myAltRowClass'
});
My Script,
var $grid = $("#ProjectSearchGrid"),
newWidth = $grid.closest(".ui-jqgrid").parent().width();
$grid.jqGrid("setGridWidth", newWidth, true); // change the grid size based on parent div size
$grid.jqGrid('setColProp','ProjectName',{width:100}); //change the column size for consistent look in the mobile device
Please include always in your questions the information about the version of jqGrid, which you use (or which you can use), and the fork of jqGrid (free jqGrid, commercial Guriddo jqGrid JS or an old jqGrid in version <=4.7).
If you use free jqGrid fork, then you can just add properties like classes: "hidden-xs", labelClasses: "hidden-xs" or classes: "hidden-xs hidden-sm", labelClasses: "hidden-xs hidden-sm" in the corresponding columns. See the demo from the old answer for more details. If you don't use Bootstrap CSS, you can add the definition of hidden-** classes manually:
#media (max-width: 767px) {
.hidden-xs {
display: none !important;
}
}
#media (min-width: 768px) and (max-width: 991px) {
.hidden-sm {
display: none !important;
}
}
#media (min-width: 992px) and (max-width: 1199px) {
.hidden-md {
display: none !important;
}
}
#media (min-width: 1200px) {
.hidden-lg {
display: none !important;
}
}
If you use an old version of jqGrid and you really can't upgrade to free jqGrid or Guriddo then you can try to use
$(window).bind("resize", function () {
// your resize handler
}).triggerHandler("resize");
and to call hideCol or showCol to hide/show the column on resizing. If you would need to follow the way, I'd recommend you to cache the list of hidden/visible columns to call hideCol or showCol only if the changes are really required. To detect the current resolution you can use window.matchMedia (see here) or to get the width of some outer div of the grid (outer div of <table id="list2"></table>).
UPDATED: I created the demo https://jsfiddle.net/OlegKi/n6g78two/, which uses jqGrid 4.6 and which demonstrates how to use window.matchMedia to hide/show some columns on resizing the grid. The demo hides the last column "ComboDuration" if the the width of view ports is 767 pixels wide or less. It uses the following code:
function hideOrShowColumns (e) {
if (e.matches) {
// we have view ports of 767 pixels wide or less
$grid.jqGrid("hideCol", "ComboDuration");
} else {
$grid.jqGrid("showCol", "ComboDuration");
}
}
var mql = window.matchMedia('(max-width: 767px)');
hideOrShowColumns(mql);
mql.addListener(function (e) {
hideOrShowColumns(e);
});
$(window).bind("resize", function () {
$grid.jqGrid("setGridWidth", $grid.closest(".my-container").width());
}).triggerHandler("resize");
You can use the methods: showCol and hideCol to hide/show columns on condition.
Note that these method accepts array as parameter to show and hide more columns at once. Docs can be found here.
By example you can do this
var $grid = $("#ProjectSearchGrid"),
$grid.jqGrid("hideCol", ["Project_Name2", "Project_Name3"]); // hide these cols before resizing
newWidth = $grid.closest(".ui-jqgrid").parent().width();
$grid.jqGrid("setGridWidth", newWidth, true);
Additionally to this if you use Guriddo jqGrid you can hide some columns when the grid loads in mobile device using the function isMobile .
By example to do this for column Project_name2 you can do
colModel: [
...
{ name: 'Project_Name2', index: 'Project_Name2', width: 140, hidden: $.jgrid.isMobile() },

Categories

Resources