I have requirement to show icon in each datatable header.now problem is icon and text are not showing in same line because of column width.what i want to increase each header cell by 50px.
Below is my code to show icon and increase width.
"fnHeaderCallback": function( nHead, aData, iStart, iEnd, aiDisplay ) {
$.each($('.table tr th'),function(key,val){
var title=nHead.getElementsByTagName('th')[key].innerHTML;
var new_width=parseInt($(nHead.getElementsByTagName('th')[key]).attr('style').split(":")[1].split("px")[0])+50 +"px"
$(nHead.getElementsByTagName('th')[key]).attr('style','width:'+new_width)
nHead.getElementsByTagName('th')[key].innerHTML = "<i class='fa fa-cube'></i>"+title;
})
}
Note : I am using dataTables 1.9.4
fnHeaderCallback() is not the right callback to use here, since it is called on each and every redraw. It is called when the user sorts, change page and so on. You should use fnInitComplete() instead.
The reason for the header titles becoming multiline is mostly caused by the browser defaults and the CSS settings (or lack of same). Add this CSS :
.dataTable th {
white-space: nowrap;
}
and add the icons in the fnInitComplete() callback :
var table = $('#example').dataTable({
fnInitComplete: function() {
$("#example th").each(function() {
var $th = $(this);
$th.html("<i class='fa fa-cube'></i>"+$th.text());
})
}
});
demo -> http://jsfiddle.net/2hLn31gp/
There should be no reason at all for manipulating the width of the headers programmatically. The widths is either
User defined widths, i.e aoColumns :[ { sWidth: "10%" }] etc
Calculated widths, where dataTables calculate the minimum width required by each column to show its content based on the table width as 100%. An attempt to increase width programmatically as above (by adding 50px to each) will increase the width to 100%+(50px*columnCount) - that is not what you want.
A combination of 1 and 2.
If you need to recalculate the width of the columns, simply recalculate them by using fnAdjustColumnSizing() :
table.fnAdjustColumnSizing();
or force the widths "manually" :
aoColumns: [
{ sWidth: "100px" },
{ sWidth: "50px" },
{ sWidth: "250px" }
]
Related
I have kendo MVC Grid and I have to set my page size to 50, so I need to freeze the column header while scrolling.
The question is : How can I freeze the column header while scrolling ?
When you create the Grid you should define the height in pixels as well as define scrollable as true.
Example:
var grid = $("#grid").kendoGrid({
dataSource: ds,
scrollable: true,
height : "150px",
columns : [
...
]
});
See this working here : http://jsfiddle.net/OnaBai/uuPW5/
Maybe this is something you were looking for:
https://github.com/jmosbech/StickyTableHeaders
Works quite well and you don't have to have scrollbars in your grid which makes it easier to work with.
You simply link provided script to your view and call this method on load:
$('#grid').stickyTableHeaders({
cacheHeaderHeight: true,
leftOffset: 1,
fixedOffset: ...
});
Parameters are optional but cacheHeaderHeight improves performance and I had to add leftOffset because of custom grid header borders and fixedOffset because of other sticky elements.
Just set the css of the grid header like this :
.k-grid-header {
position: sticky;
top: 0;
}
This answer has already been given for kendo UI, but here is how it's implemented for kendo MVC:
.Scrollable(scr => scr.Height(400))
It will give you a vertical scroll bar, allowing the user to scroll through the data while constantly seeing both the header and footer of the table. You can read more about it here: https://docs.telerik.com/aspnet-mvc/html-helpers/data-management/grid/scrolling/overview.
Trouble with this solution, however, is that the grid will be 400px tall, even when there is only one row of data. You can solve this like so
.Scrollable(scr =>
{
if (data.Count() < 10)
{
scr.Height("auto");
}
else
{
scr.Height(400);
}
})
I've got a grid that's width is 100%. The columns size equals out among all columns when the grid first loads.
The user can then re-size columns to fit their need.
Now I need a way to reset all the columns back to defaults without reloading the page.
I tried refreshing the grid but that didn't work after the grid has already been bound:
.data().kendoGrid.refresh()
You might try a little trick (this is not perfect and might fail depending on your custom grid formatting). The trick is setting the widths to the same amount (ex. 100px). Something like:
Grid definition:
var grid = $("#grid").kendoGrid({
dataSource: ds,
resizable : true,
pageable : true,
columns :
[
{ field: "FirstName", title: "First Name" },
{ field: "LastName", title: "Last Name" },
{ field: "City" }
]
}).data("kendoGrid");
Code for resizing:
$("col", grid.element).css("width", "100px");
In addition, you might be interested on doing:
$("table", grid.element).css("width", "100%");
This resizes the "table" columns to use all the original space otherwise (just doing the col resizing) you might end-up with equally spaced cols but not using all the original width of the table).
You can see how it works here: http://jsfiddle.net/OnaBai/a9QSr/
I am wanting to use Collapsible DIVs to show and hide content from the user.
I found this jQuery code to do the expand and collapse:
http://webcloud.se/code/jQuery-Collapse/
However the content is already loaded in the divs (its just hidden from view).
So I then found this:
http://www.raymondcamden.com/index.cfm/2011/4/5/Collapsible-content-and-Ajax-loading-with-jQuery-Mobile
Which loads the content into the opening div but also unloads it when it closes!
However its all mixed in with jQuery mobile and so it styled.
I want to be able to style the divs myself. also the first example uses nice bounce or fade effects to bring the content into view.
The reason for doing this is I want to show the user different content such as images or flash files but I don't want everything to load into the page on page load, this would be too much stuff.
So how can I use the first jQuery Collapse example but with loading external pages in?
I liked the question so I spent a little time making something close to a plugin:
//only run the event handler for collapsible widgets with the "data-url" attribute
$(document).delegate('.ui-collapsible[data-url] > .ui-collapsible-heading', 'click', function () {
//cache the collapsible content area for later use
var $this = $(this).siblings('.ui-collapsible-content');
//check if this widget has been initialized yet
if (typeof $this.data('state') === 'undefined') {
//initialize this widget
//update icon to gear to show loading (best icon in the set...)
$this.siblings('.ui-collapsible-heading').find('.ui-icon').removeClass('ui-icon-plus').addClass('ui-icon-gear')
//create AJAX request for data, in this case I'm using JSONP for cross-domain abilities
$.ajax({
//use the URL specified as a data-attribute on the widget
url : $this.closest('.ui-collapsible').data('url'),
type : 'get',
dataType : 'jsonp',
success : function (response) {
//get the height of the new content so we can animate it into view later
var $testEle = $('<div style="position:absolute;left:-9999px;">' + response.copy + '</div>');
$('body').append($testEle);
var calcHeight = $testEle.height();
//remove the test element
$testEle.remove();
//get data to store for this widget, also set state
$this.data({
state : 'expanded',
height : calcHeight,
paddingTop : 10,
paddingBottom : 10
//add the new content to the widget and update it's css to get ready for being animated into view
}).html('<p>' + response.copy + '</p>').css({
height : 0,
opacity : 0,
paddingTop : 0,
paddingBottom : 0,
overflow : 'hidden',
display : 'block'
//now animate the new content into view
}).animate({
height : calcHeight,
opacity : 1,
paddingTop : $this.data('paddingTop'),
paddingBottom : $this.data('paddingBottom')
}, 500);
//re-update icon to minus
$this.siblings('.ui-collapsible-heading').find('.ui-icon').addClass('ui-icon-minus').removeClass('ui-icon-gear')
},
//don't forget to handle errors, in this case I'm just outputting the textual message that jQuery outputs for AJAX errors
error : function (a, b, c) { console.log(b); }
});
} else {
//the widget has already been initialized, so now decide whether to open or close it
if ($this.data('state') === 'expanded') {
//update state and animate out of view
$this.data('state', 'collapsed').animate({
height : 0,
opacity : 0,
paddingTop : 0,
paddingBottom : 0
}, 500);
} else {
//update state and animate into view
$this.data('state', 'expanded').animate({
height : $this.data('height'),
opacity : 1,
paddingTop : $this.data('paddingTop'),
paddingBottom : $this.data('paddingBottom')
}, 500);
}
}
//always return false to handle opening/closing the widget by ourselves
return false;
});
The collapsible HTML looks like this:
<div data-role="collapsible" data-url="http://www.my-domain.com/jsonp.php">
<h3>Click Me</h3>
<p></p>
</div>
Here is a demo: http://jsfiddle.net/YQ43B/6/
Note that for the demo I found the best way to make the initial animation smooth was to add this CSS:
.ui-mobile .ui-page .ui-collapsible .ui-collapsible-content {
padding-top : 0;
padding-bottom : 0;
}
The default padding added by jQuery Mobile is 10px for both top and bottom paddings, I added those values as data-attributes to each widget to maintain the defaults.
Note that this code can be slightly tweaked to show other types of content, I used JSONP simply because you can use it on JSFiddle.
Here is an example that I made :
$(document).ready(function () {
$('.accordian_body').hide();
});
$('.accordian_head').click(function () {
$(this).next().animate(
{ 'height': 'toggle' }, 'fast'
);
Then in HTML
<div class="accordian_head"></div>
<div class="accordian_body"></div>
in CSS you can style the head and body however you like , to add in code behind -
<asp:Literal ID="lit1" runat="server" />
foreach(DataRow dr in DataTable.Rows)
{
lit1.Text = lit1.Text + "<div class=\"accordian_head\">" Whatever you want... "</div><div class=\"accordian_body\">" Whatever in body "</div>
}
Check this link it's in php and shows how to load external link to DIV Ajax can load only internal pages and doesn't work across domains.
Ive been through all the posts, finally got setCell to work with hardcoded values, but not using the options.rowId.
function StatusFormatter(cellvalue, options, rowObject) {
if (cellvalue == 'C'){
jQuery("#list").setCell(options.rowId , 'SOORDLINE', '', { color: 'red' });
jQuery("#list").setCell("[2.000]", 'SOORDLINE', '', { color: 'red' });
jQuery("#list").setCell('[2.000]', 'SOREQDATE', '', { color: 'red' });
jQuery("#list").setCell(options.rowId, 'SOPRICE', '', { color: 'red' });
}
return cellvalue;
};
The FIRST and LAST lines dont work, but the 2 with the hardcoded rowId DO work. I inspected what comes back in the option.rowId and they are the same as the hardcoded values, (just different depending on the row of course. What am I missing? Please help. I dont see any difference between the lines, or values.
EDITED-
I tried the answer, and it seems to be what I need. I tried the following
{ name: 'SOORDLINE', index: 'SOORDLINE', width: 25, search: false ,celattr: function () { return ' style="color: red"'; }
},
To aleast make them all red before I dove into the logic, and it didnt do anything for me.
Sorry, but you use custom formatter in absolute wrong way. The goal of the custom formatter to to provide HTML fragment to fill the content of the cells in the corresponding column. So the StatusFormatter will be called before the row with the id equal to options.rowId will be created. Moreover for performance purpose one use typically gridview: true. in the case the whole content of the grid (the whole body of the grid) will be constructed first as string and only after that will be placed in the grid body in one operation. It improve the performance because after placing of any element web browser have to recalculate position of all other elements on the page.
If you want to set text color on the SOORDLINE cell you should cellattr instead:
celattr: function () { return ' style="color: red"'; }
The celattr can be used also in the form celattr: function (rowId, cellValue, rawObject) {...} and you can test the property of rawObject which represent of the values for any column and return the cell style based on the cell value.
Alternatively you can enumerate the rows inside of loadComplete and set the style on <tr> element instead of setting the same styles for every row. See the answer as an example.
I added the resizeStop event to my grid and it gets called, but I need to save the new column widths in the session and then use the new values to maintain the user preferences for column widths. Currently paging in the grid or reloading resets the column widths.
Here is what I have so far.
resizeStop: function(newwidth, index) {
alert(index + " : " + newwidth);
}
OK, I got it. I store all column widths in a HashMap in a bean I use to save session info. When the resizeStop event is fired I submit the new column size to a controller (I'm using Java and Spring) which updates the values in the HashMap.
Here are the code snippets:
resizeStop: function(newwidth, index) {
var colModel = $("#list").jqGrid('getGridParam','colModel');
$.post("/sessionState/columnWidth/update",
{
column: colModel[index].name,
width: newwidth
}
)
}
and in the colModel:
{name:'Title', index:'title', width: ${uiState.columnWidthMap["Title"]}, jsonmap: 'title', sorttype: "text"}