A better way to determine even/odd rows in table - html

Say you have a webpage with following sample code:
<tr class="even">
<td>something1</td>
<td colspan="1">somthing1.1</td>
</tr>
<tr class="odd">
<td>something2</td>
<td><b>something2.1</b></td>
</tr>
<tr class="even">
<td>something3</td>
<td><b>something3.1</b></td>
</tr>
These are not in a loop so I have to explicitly say 'even' 'odd'. Later on if we decide to add a new row between something2 and something3 then we need to change 'even' 'odd' for rest of the rows as well.
Is there way in css to do this automatically in IE6?
Currently this is my css code for even
.headerTable tr.even {
font-weight : bold;
font-size : 9pt;
font-family : Arial,Helvetica,sans-serif,Verdana,Geneva;
background-color: #FFFFFF;
height: 20px;
color: #000000;
}
I already had jQuery

The way to do this would be to use the nth-child(even) and (odd) rules. Unfortunately, and this should come as no surprise, IE6 does not support this. So you have a few options:
A) Use Javascript, with the obvious drawback of it not working for people with JS disabled:
var rows = document.getElementById('mytable').getElementsByTagName('tr');
for(var x = 0; x < rows.length; x++) {
rows[x].className = (x % 2 == 0) ? 'even' : 'odd';
}
If you expect to need more dynamic client side behavior on your application, you could then check a library like jQuery out. For just this it is unnecessary, but it makes working with Javascript across browsers a breeze. You would do the above with jQuery like it is shown in this answer.
Depending on your audience, Javascript may be perfectly acceptable. If it's not, then maybe you can...
B) Simplify your CSS and keep doing it manually. You can only mark the odd rows with a class, and then make the row default style the even styling. This will save you some work when moving things around.
C) Generate the rows programmatically. It is really archaic to be entering data like that into a fixed table if you're going to be updating it often enough that this is a problem. I'm obviously oblivious to your circumstance, but it should be trivial to do this in a loop somehow with a simple language like PHP.
D) Stop using a really outdated browser. :) (This is only half joking, as I'm sure its out of your control)

Give jQuery a try. Then you can simply do this:
$("#myTable tbody tr:visible:even",this).addClass("even");
$("#myTable tbody tr:visible:odd",this).addClass("odd");
The ":visible" selector isn't really necessary, but when you filter a table by making some rows hidden, the method will still work correctly.

The best approach would be the :nth-child() pseudo-class.
But unfortunately it’s not widely supported yet. So you’ll probably need to use JavaScript to do that.

Use jQuery's even/odd child implementation

Yes. You can use JavaScript to run through these elements and reset their classes according to even/odd.

Related

bootstrap table hide before filtering

I have a bootstrap html table. filtering is used in the field. how do I make sure that the table contents are hidden before filtering starts?
filter script and html table:
$(document).ready(function(){
$("#surname").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("#table tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
<table class="table" id="table">
<thead class="thead-light">
<tr>
<th></th>
<th class="text-center" scope="col">Guest</th>
<th class="text-center" scope="col">Org</th>
Bootstrap v4 uses d-none for setting anything to "display: none".
Set each on each <tr class="d-none"> and they will be hidden on default. In your code, just after you filtered everything, let's show them again using jquery (not tested):
/* ... */
$("#table tr").filter(function () {
const show = $(this).text().toLowerCase().indexOf(value) > -1;
if (show) {
$(this).removeClass('d-none');
}
});
This post is more of a comment on BS-4 than anything....
Your requirement is very simple - first hide all the tr's and then on the filter - show the ones that meet the requirement.
Soap box moment -
I am not in favour of the new BS-4 utility classes and use of "!important" on everything.... to the casual observer - it may well be nice to simply apply the class to the elemnet and get the outcome - but when you look at the code or the less files from BS - EVERY SINGLE UTILITY CLASS IS STYLED WITH "!IMPORTANT"....
this can be seen in the following picture which shows a span with 4 utility classes - and ALL four classes are styled with the use of !important..... that alone is enough to make me re-consider BS as a viable option for creating sites - imagine all the important tags that you will have.
I also do not love the new approach of using a utility for every single style choice... imagine a div with 4 different margins styles, four different paddings, and four different border styles..... a utility class for each.... eek
Just my opinion - but for something as simple as display: none... do it with css and leave off the !important.

Table cells shifting in IE9 [duplicate]

My website has always run smoothly with IE8, IE7, FF, Chrome and Safari. Now I'm testing it on IE9 and I'm experiencing a strange problem: in some pages, some tabular data renders incorrectly.
The HTML source is correct and all, and the row giving the problem changes every time I refresh the page (to tell the truth, the problem itself appears only in some refresh, not all).
Using the F12 Tool of IE, the table structure appears correct, there should be no empty TD after the TD containing M08000007448, but still it renders like this.
Moreover, if I use the F12 tool, with "select element by click" tool in the toolbar, and I try to click on the empty space between M08000007448 and 19 , it selects the TR, not a "hidden td".
I'm having this table rendering problem also in some other table in the application, anyone experiencing something like this? It happens only in IE9 :(
I don't know if it's important, but the page is made with ASPNET (webforms) and use Jquery and some other JS plugin.
I tried to save the page (with images) and open it in local with IE9, but the problem never occurs. (Of course I checked all the table structure and it's ok. Header and all rows have the eact same number of TD's, with the right number of colspan when necessary).
I have exactly the same problem as well. you may want to read this https://connect.microsoft.com/IE/feedback/details/649949/innerhtml-formatting-issues-on-very-large-tables
YOu can remove the space inbetween td by using javascript if your html is returned from ajax, then from the response, you replace it with
response_html = response_html.replace(/td>\s+<td/g,'td><td');
$('#table').html(response_html);
I had the same exact issue populating a table using jquery templates. I kept having 'ghost' <td>'s on larger datasets (300+) only in IE9. These <td>'s would push the outer columns outside the boundries of my table.
I fixed this by doing something really silly; removing all the spaces betwen the <td> start and end tags and left justifying the HTML markup pertaining to my table. Basically, you want all of your <td> </td> on the same line, no spaces.
Example:
<table>
<tr class="grid_customer_normal">
<td>${primary}</td>
<td>${secondary}</td>
<td>${phone}</td>
<td>${address}</td>
</tr>
</table>
The solution given #Shanison helps only partially but the problem persists if there are spaces between any of the other elements that can be part of the table content model like thead, th etc.
Here is a better regex devised by my Lead at work.
if (jQuery.browser.msie && jQuery.browser.version === '9.0')
{
data = data.replace(/>\s+(?=<\/?(t|c)[hardfob])/gm,'>');
}
covering all table, caption, colgroup, col, tbody, thead, tfoot, tr, td, th elements.
Note: jQuery.browser was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin. Please try to use feature detection instead.
I fixed this issue by removing the whitespace:
var expr = new RegExp('>[ \t\r\n\v\f]*<', 'g');
var response_html_fixed = data.replace(expr, '><'); //A disgusting hack for ie9. Removes space between open and close <td> tags
$('#treegrid-data').replaceWith(response_html_fixed);
IE Blog mentions a new tool today called the Compat Inspector script to help troubleshoot IE 9 rendering incompatibility. It may help troubleshoot your issue.
http://blogs.msdn.com/b/ie/archive/2011/04/27/ie9-compat-inspector.aspx
I was having that problem too.
It occured to me, that width attribute in td/th tags causng this problem.
Changed it to style="width: XXpx" and problem is solved :)
I ran into this problem as well and I realized that it happened when I was directly putting text in <td> elements. I'm not certain whether it's a standard or not but after wrapping any text in <span> elements, the rendering issues disappeared.
So instead of:
<td>gibberish</td>
try:
<td><span>gibberish</span></td>
Found a very useful script to prevent unwanted cells in your html table while rendering.
function removeWhiteSpaces()
{
$('#myTable').html(function(i, el) {
return el.replace(/>\s*</g, '><');
});
}
This javascript function you should call when the page loads (i.e. onload event)
Late answer, but hopefully I can help someone with this.
I experienced the same problem when debugging in IE9. The solution was removing all whitespaces in the HTML code.
Instead of
<tr>
<td>...</td>
<td>...</td>
</tr>
I had to do
<tr><td>...</td><td>...</td></tr>
This seemed to solve the problem!
This is the very serious bug in IE9. In my case removing only white spaces between different td was not sufficient, So i have removed spaces between different tr also. And it is working fine.
I had similar problem with ie-9 when rendering dynamic table.
var table = $('<table><tr><td style="width :100"></td></tr></table>');
when rendered translates to...
<table><tbody><tr><td style="width :100px"></td></tr></tbody></table>
this works perfectly fine in ie=10 chrome safari...
// but for ie-8 it renders to... with a style attr in my case
<table><tbody><tr><td ></td></tr></tbody></table>
you need to write 100px instead of 100.
Having same formatting issue with ie9, and a new issue in ie11 where it formats correctly but takes 25-40 seconds to render a table of about 400 rows and 9 columns. It has the same cause, whitespace inside the tr or td tags.
I'm displaying a table that is created by the rendering of a partial view from an AJAX call. I decided to BFH it on the server by removing the whitespace from the rendered partial view, using a method posted here: http://optimizeasp.net/remove-whitespace-from-html
This is his solution copied in-toto:
private static readonly Regex RegexBetweenTags = new Regex(#">(?! )\s+", RegexOptions.Compiled);
private static readonly Regex RegexLineBreaks = new Regex(#"([\n\s])+?(?<= {2,})<", RegexOptions.Compiled);
private static string RemoveWhitespaceFromHtml(string html)
{
html = RegexBetweenTags.Replace(html, ">");
html = RegexLineBreaks.Replace(html, "<");
return html.Trim();
}
And here is a method that returns a partial view as a string, stolen from another SO answer:
public string RenderPartialViewToString(string viewName, object model)
{
this.ViewData.Model = model;
try
{
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
viewResult.View.Render(viewContext, sw);
return RemoveWhitespaceFromHtml(sw.ToString());
}
}
catch (Exception ex)
{
//logger here
}
}
It takes a bit of time, but less than a second to render a table of about 400 rows, which for my purposes is good enough.
I had this problem sometimes on tables generated by Knockout. In my case I fixed it using the jQuery solution found here
jQuery.fn.htmlClean = function() {
this.contents().filter(function() {
if (this.nodeType != 3) {
$(this).htmlClean();
return false;
}
else {
this.textContent = $.trim(this.textContent);
return !/\S/.test(this.nodeValue);
}
}).remove();
return this;
}
I had the same issue with KendoUI grid in IE10. I was able to force IE to rerender missing table cells with this hack:
htmlTableElement.appendChild(document.createTextNode(''));
Appending an empty textNode makes IE to rerender the whole table.

Multi-column Headers With Kendo Grid

I don't know what this is called, and I've messed around a lot with the headerTemplate but can't figure out how to produce this look. I need the second row of column names to 'act normally' in terms of sorting and filtering, but everything I try breaks that. I have no idea if headerTemplate is even the right way to do this? Is there a name for this kind of grouping? My research is turning up a whole lot of nothing, so I suspect I'm using the wrong keywords. What is this layout called?
Note: for security reasons I can't post a code dump (super nervous about the image too). If a specific thing is needed, please let me know and I'll try to anonymize it. But, mostly I'm just looking for suggestions to try other than playing with the headerTemplate.
This is now natively supported by the Kendo grid. Here's an example.
You won't be able to achieve multirow Group headers via Kendo grid on MVC, although there were discussion to add the feature in the current version(2014Q2) of Kendo. See below link for more reference:
Pivot Grid StackOverflow Reference
However, you can achieve the multirow header option via jquery on databound event of the grid. But it is a workaround rather than a perfect soultion.
Please see the js function for databound event to add multirow header:
function onDataBound(arg) {
var myElem = document.getElementById('trParentHeader'); //Check if Parent Header Group exist
if (myElem == null){ // if parent Header doesnot exist then add the Parent Header
$("#grid").find("th.k-header").parent().before("<tr id='trParentHeader'> <th colspan='2' class='k-header'><strong>Products + Unit Price</strong></th> <th scope='col' class='k-header'><strong>Single Units in Stock</strong></th></tr>");
}
}
For more understanding and a working example please see below Sample:
MultiRow-Column Header Sample
Please let me know if you if you have any queries.

Can I specify maxlength in css?

Can I replace the maxlength attribute with something in CSS?
<input type='text' id="phone_extension" maxlength="4" />
No.
maxlength is for behavior.
CSS is for styling.
That is why.
No. This needs to be done in the HTML. You could set the value with Javascript if you need to though.
You can use jQuery like:
$("input").attr("maxlength", 4)
Here is a demo: http://jsfiddle.net/TmsXG/13/
I don't think you can, and CSS is supposed to describe how the page looks not what it does, so even if you could, it's not really how you should be using it.
Perhaps you should think about using JQuery to apply common functionality to your form components?
Not with CSS, no.
Not with CSS, but you can emulate and extend / customize the desired behavior with JavaScript.
As others have answered, there is no current way to add maxlength directly to a CSS class.
However, this creative solution can achieve what you are looking for.
I have the jQuery in a file named maxLengths.js which I reference in site (site.master for ASP)
run the snippet to see it in action, works well.
jquery, css, html:
$(function () {
$(".maxLenAddress1").keypress(function (event) {
if ($(this).val().length == 5) { /* obv 5 is too small for an address field, just want to use as an example though */
return false;
} else {
return true;
}
});
});
.maxLenAddress1{} /* this is here mostly for intellisense usage, but can be altered if you like */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" class="maxLenAddress1" />
The advantage of using this: if it is decided the max length for this type of field needs to be pushed out or in across your entire application you can change it in one spot. Comes in handy for field lengths for things like customer codes, full name fields, email fields, any field common across your application.
Use $("input").attr("maxlength", 4)
if you're using jQuery version < 1.6
and $("input").prop("maxLength", 4)
if you are using jQuery version 1.6+.

How to alternate HTML table row colors using JSP?

How do I alternate HTML table row colors using JSP?
My CSS looks something like:
tr.odd {background-color: #EEDDEE}
tr.even {background-color: #EEEEDD}
I want to use <c:forEach> to iterate over a collection.
<c:forEach items="${element}" var="myCollection">
<tr>
<td><c:out value="${element.field}"/></td>
...
</tr>
</c:forEach>
I need an int count variable or boolean odd/even variable to track the row. Then my <tr> tag would look something like:
<tr class="odd or even depending on the row">
Use the varStatus attribute on your forEach tag and JSTL will manage an instance of a javax.servlet.jsp.jstl.core.LoopTagStatus for you in the variable name you specify.
You can then use a ternary operator to easily output the appropriate class name:
<c:forEach items="${element}" var="myCollection" varStatus="loopStatus">
<tr class="${loopStatus.index % 2 == 0 ? 'even' : 'odd'}">
...
</tr>
</c:forEach>
This JSTL primer from IBM has more information about the core tag library and what it gives you.
Just do like this and is going to work:
table tr:nth-child(odd) { background-color: #ccc; }
If you are willing to make this happen on the client side, you can do Zebra Striping with JQuery.
It would be done with just a couple lines of code, but you would have to include the jquery library in your file.
http://docs.jquery.com/Tutorials:Zebra_Striping_Made_Easy
http://docs.jquery.com/Selectors/odd
http://docs.jquery.com/Selectors/even
(this answer only pertains to the CSS side of things...)
As a matter of course, I always target the child TD's like so:
tr.odd td {}
tr.even td {}
The reason being is that IE actually applies TR background-color by removing the value set on the TR and applying it to each individual TD within that TR. Sometimes you might have a css reset or other css rules that overrides IE's strange way of doing TR background-color, so this is a way to make sure you avoid that.
Also, you might want to consider setting just
tr td {background-color: #EEDDEE}
and
tr.odd td {background-color: #EEEEDD}
so your code is slightly less verbose
I don't use JSP, so I can't give you an answer in your language, but here's what I do (using pseudo code)
counter = 0
foreach (elements)
counter = counter + 1
output: <tr class="row{counter % 2}">...</tr>
Personally, I name the classes "row0" and "row1", which lets you alternate between them with a simple modulus calculation, also, if you decide to have rows alternating in triples or quads (instead of pairs), you can easily extend it to row2, row3 and change your output code to be counter % 4, etc.
I've used a tertiary operator in cases like this. It would look something like:
String oddEven="";
<c:forEach items="${element}" var="myCollection">
oddEven = (oddEven == "even") ? "odd" : "even";
<tr class='"'+oddEven+'"'>
<td><c:out value="${element.field}"/></td>
...
</tr>
</c:forEach>