Using jQuery to customize the styles in table cells
Originally posted on ChrisHammond.com
I was trying to do some work with the Form and List module in DotNetNuke today and I needed to apply some custom styles to the LIST view of a module, without going in and creating a full XSL template for the module to use, I wanted to style the default table based grid view.
In order to customize this view though I needed to do some custom jQuery that runs after the table is loaded, the jQuery then goes through and looks for columns, and based on the number of columns, adjusts the way those columns display.
First I wanted to make it so that a specific column didn’t have text wrapping, which in HTML would normally use the nowrap property on a column, but because of the dynamic nature of F&L you can’t configure that manually. To achieve this I needed to loop through each Table Row (TR) in the table, and then find the column in question, and apply the css attribute/value for white-space/nowrap. To do this I used code like the following.
$("#tableId tr").each(function(){
var cellCount = $(this).find("td").length;
if(cellCount==4)
{
$(this).find("td:eq(0)").css("white-space","nowrap");
}
else
{
$(this).find("td:eq(1)").css("white-space","nowrap");
}
});
Basically that goes through and finds each row in the table, then checks to see how many columns there are. I do this because the VIEW for the table when you are logged in, versus when you aren’t logged in, is different, the F&L module adds an Edit column at position 0, so you can see in the ELSE statement I basically want to set the width on the 2nd column, position 1 in the zero-based array.
If you want to do something similar for the HEADER row of the table you have to do things slightly differently, using the following code
$("#tableId tr:eq(0)").each(function(){
var cellCount = $(this).find("th").length;
if(cellCount==4)
{
$(this).find("th:eq(0)").css("text-align","left");
$(this).find("th:eq(1)").css("text-align","left");
}
else
{
$(this).find("th:eq(1)").css("text-align","left");
$(this).find("th:eq(2)").css("text-align","left");
}
});