DataTable Fundamentals Part 1

I’m a big fan of jQuery DataTables. It’s my new grid of choice for interfacing. I jumped on the bandwagon at at the release of 1.10.0 which was a major versioning change/re-working. The documentation was lacking a bit at the time so I had to do a lot of trial and error to figure things out. I used jqGrid for years before making the transition. I find DataTables to be cleaner (as far as object organization) and more understandable. I feel that any programmer that comes behind me will have an easier time deciphering code I’ve written for DataTables verses jqGrid. It also looks more like a table to me as opposed to some kind of widget. You can probably accomplish more advanced things with jqGrid, but a lot of that is unnecessary fluff that doesn’t lend itself to the real, business world.

Display Values

Some trivial features alluded me at first. Such as how do I modify the display without compromising the underlying data? Some record values don’t translate well for users. For instance, in a database record you may have a field with a value of stdenv, but you want to show it as Standard Envelope to the user. If your code continues to interact with the database you may need to retain that original value.

In jqGrid you would often use a formatter. To translate a date you may do something like this:
So how do you do this in DataTables? When working with this plugin I’m almost always using an ajax data source as objects. I thought I was translating this correctly by manipulating the ajax result via the ajax property but later found out that was changing the underlying data. Then I discovered I could change it in the createdRow property. That technique was okay but for every cell that renders there is two DOM writes (the write by the plugin, then my translated overwrite). Finally, I came across an elegant solution that makes me happy. I already have a columns property defined in my DataTable object:
To translate a value I use the render property. You can read about it here. It can be as simple as this:
You can also translate the data in these types of ways:
To set a default value use the defaultContent property. You can read about it here:

Sub-Sorting

Sometimes you want your grid to sub-sort related columns when sorting on a column. This is simple to declare as well using the orderData property. You can read about it here:
The column indexes are in the order they appear: name: 0, position: 1, date: 2. So clicking on position will sub-sort name. Likewise, sorting descending on position will sub-sort descending on name.

Read More

Show Bootstrap Tooltip Over Truncated Text

I had a need to prevent text-wrapping in a cell. I wanted the text to appear truncated to keep the row height consistent. The following worked well to crop the text and show an indicator … of hidden text:
I referenced the classes like so:
Next, I wanted the user to be presented a tooltip if the text was truncated so they could see the full value. Here is my solution:
This snippet watches for mouse placement over the DIV. It then does some width comparisons to see if there is any hidden text. If so it creates a tooltip using Twitter Bootstrap and displays it. Simple as that.

BTW, you are not limited to simple tables. This will also work with jQuery Datatables. See my post on Datatable Tweaks.

See a DEMO.

Read More

Ajax Script Loading that Enforces Order of Execution

One awesome feature of jQuery is the ability to load external scripts on demand. The $.getScript method loads the script behind the scenes via ajax. In fact the function is simply an alias to call to jQuery’s $.ajax function. By default that alias does not look for a cached items. In my particular need I wanted to observe a cache and guarantee order of execution. I resorted to using the $.ajax function directly since it offers more options. I did not want a script to load before it’s dependency nor did I want to bog down my page by doing synchronous requests. In no time at all I built my own mechanism to handle script requests.

My code basically loads one script at a time and waits until it is completely loaded before iterating to the next file. Once they are all loaded it will call the loadComplete function which can take advantage of those scripts. This method will load scripts as memory and resources are available, then perform the final action when complete. The user could be presented a loading gif or progress bar in the meantime.

Below I am showing an example using CDN scripts:

Read More

jQuery Select2 Validation

Since my recent post for jQuery TE Validation seems to be popular ( at least for my site ūüôā ) I thought I would demonstrate how to validate another plugin that doesn’t work right out the gate. I’m referring to the Select2 plugin. It is a jQuery replacement for SELECT boxes with a BootStrap type of look. It can product a listbox similar to Facebook’s popular multi-select style. Other options include list item images, searching, sorting (with drag & drop), infinite scrolling, and much more. We will be validating it with the jQuery Validation plugin.

This example uses the following external sources. All of them can be referenced through a Content Delivery Network:
Alternatively, you can go to the plugin sites and retrieve the individual files, or simply install nugets if using .NET.

Now let’s add some markup to the page. The code below covers Select2s that are made in a traditional sense with SELECT tags. If you are creating Select2s with dynamic options (which uses an INPUT[HIDDEN] instead) then I have solution as well. See the second DEMO at the bottom of this tutorial. Here, I’m creating a form with three different types of elements to validate. Each of them have the "required" class which is auto-detected by the jQuery validation plugin. Of course you’re mainly concerned with Select2 but the additional fields are good for a visual comparison when validation fails.
Now let’s add some CSS. Most of this is basic styling besides the myErrorClass portions, which are used to handle validation errors. In our jQuery Validation script we will set it to be our error class. If something fails it will put that class on both the element and an error label. In our script we manipulate the error label to appear behind our element. The !important keyword is needed to override default select2 styling. If all goes well then users should see a striped background on invalid elements as well as a red message describing the error in more detail beneath it.
And finally we add the script. I’ve placed comments throughout to explain the various components:
That’s it! With these adjustments Select2 will have the same look and feel as the rest of your form elements when validating. Leave me a one-liner if you found this useful.

See a DEMO. View this DEMO if loading options dynamically. If this post has helped you then upvote my answer on StackOverflow.

Thanks.

Read More

Accessible FontAwesome Image Buttons

FontAwesome is a cool resource to use in web development. As its name suggests it is a font (like webdings/wingdings), except it has images that are actually useful. Some icons include edit, delete, email, save, lock, comment, search, facebook logo, etc. But since it’s a font some may wonder how to use it in an accessible way. Here is an example of an edit button:
Some of the classes being referenced are:
This example places an edit icon on an empty BUTTON tag with the fa fa-edit classes. I have also included CSS to remove the browser styling related to the BUTTON tag. Within the button tag is a SPAN tag with the value of Edit. It, however, is floated off the page and can only be detected by screen readers. The reader should say Edit Button. If CSS is completely disabled the image will not be shown but the text won't be hidden either. You are still left with a button whose purpose is understandable!

Read More

Alternative to Using Tables for Layout

Most developers are familiar with tables and how they behave. They have relied on them heavily in the past to display data as well as templating and design. But as we learned in my previous post you are no longer encouraged to use them for layouts. You should use CSS instead.

When I first started dabbling with DIV tables I used the CSS float property to mimic cells. But in many situations that method forced me to be overly specific on the heights and widths of my cells. It seemed to be two-times the work. Also vertical alignment and centering was much more difficult.

But luckily CSS3 has a solution for us with the DISPLAY property: table, table-row and table-cell.

In the following example I have some HTML:
And when you include a little CSS:
Above, I am showing how to easily center a table with auto-sized columns and rows based on the content. I’m also vertically and horizontally aligning a cell with ease. Heights and widths were not required. The height that was set was only to demonstrate vertical-alignment.

The CSS display properties work in all major browsers. They became fully functional as of IE9 but can work in IE8 with an additional meta tag. See this post for more information. IE8 was released on March 19, 2009 and IE9 on March 14, 2011.

Remember that it is just as bad to use tables for layout as it is place tabular data into a DIV table. Tables still have a purpose! If you are confused on when to use each then you may find a better understanding in my previous post.

See a DEMO.

Enjoy.

Read More

When and How to Use Tables

If you are web developer then you have probably heard at some point NOT to use tables for layout. This has to do with best practices for website accessibility. But what really are the rules? The WC3 defines the table model as follows:

The HTML table model allows authors to arrange data — text, preformatted text, images, links, forms, form fields, other tables, etc. — into rows and columns of cells.
On the same page it also mentions that you should not use tables for layout:

Tables should not be used purely as a means to layout document content as this may present problems when rendering to non-visual media.

With that being said, it is perfectly fine to use tables for textual data that can be organized into columns and rows. It is also fine if hyperlinks or image-links are included with the data (i.e., email links). Tables can also be used for input as well. Feel free to use textboxes, dropdowns and other form elements if they all tie to a single record of information.

So what about headers? Are they required? They are required if you are adhering to Section 508 standards for web accessibility:

(g) Row and column headers shall be identified for data tables
(h) Markup shall be used to associate data cells and header cells for data tables that have two or more logical levels of row or column headers.

The presence of table headers help eliminate confusion for both visual and non-visual user agents. The "markup" mentioned above can be performed as follows:

Table Header or <th> cells have a scope attribute. It tells the screen reader whether the header is for a column (col) or for a row (row).

Table Data or td cells have a headers attribute. It contains the id(s) of any <th> cells that apply to it, delimited by spaces.

Scope and headers fulfill the same function so you can choose one or the other. While screen readers may correctly guess whether a header is for a column or row based on table layout, clarifying with one of the above methods makes this unambiguous. However, Section 508 demands the markup if multiple headers are involved.

Abbreviations can also assist in markup:
They can be used for clarification, space-saving (for minimalistic user agents), and repetitive rendering (i.e., speech synthesizers may restate the <th> abbreviated value before reading each associated <td> value).

Hopefully this helps clarify some questions and aids in future development.

Read More

jQuery TE Validation

In one of my latest projects I utilized the jQuery Validation Plugin to handle the error validation of a page. It is a popular plugin that examines all elements in a form and validates them based on rules and/or classes. For instance, you can set a class on an textbox to be "email" and it will notify the user (as they leave the element) if the data they entered has correct email syntax.

One of the fields in my page was a rich text editor (WYSIWYG) using the jQuery TE Plugin. Unfortunately, validation would not work with it because of the way it manipulates the textarea. The plugin forces users to interact with an Input DIV (a DIV that uses the contenteditable attribute), while the textarea is hidden and populated behind the scenes.

Sample HTML:
I begin by transforming the textarea into a WYSIWYG by calling the "jqte" method. I then override the default behavior of the validator plugin by including invisible elements in validation. Normally it would ignore the textarea since it can't be seen.
I then initialized my validation object so it will monitor the form. The plugin enumerates through the targeted form’s elements and detects the "required" class on my textarea. Below we also specify a custom error class (maskError) to be used for our error label. We then manage the placement of the error label. By default the validation plugin will stick the message after an element. With jQuery TE, the textarea is placed in a hidden DIV, so the error label cannot be seen if it is placed there. Since a Parent DIV surrounds the whole widget, it is better positioned after it. Next, we override the highlight and unhighlight functions so that the errorClass will also be added/removed from the widget's Parent DIV.
Next, our CSS will come into play. If our errorClass is set it will put a red border and striped background on the widget. This simply accommodates the error message.
Next, we intercept the "blur" event of the Input DIV. Here I am checking to see if the form has been submitted or not. If so then I revalidate the form each time a user leaves the WYSIWYG, which in turn, sets or removes the visual error indicators.
Lastly, we wire-up the click event of the button to submit the form. We are displaying an alert to show everything is valid. You can actually bypass that and just submit the form and it will invoke the Validator plugin.
This seemed to do the trick for me and made the WYSIWYG behave like the other form elements on the page.

See a DEMO.

Enjoy.

Read More

jQuery Masked Input Plugin

Today I want to discuss a jquery plugin that I have found to be useful.  It is the Masked Input Plugin.  It does three things: gives a visual representation to the client of the format of data we require, ensures they enter it that way, and does immediate validation.

Here is an example of a mask a user could see for phone input:
(___) ___-____

The mask is shown when the textbox receives focus. Underscores indictate where the user should type. Your mask restricts what you can type, and you cannot type anything beyond the mask.

Masks Rules:

When building your mask there are reserved characters with preset meanings:
  • a – Represents an alpha character (A-Z,a-z)
  • 9 – Represents a numeric character (0-9)
  • * – Represents an alphanumeric character (A-Z,a-z,0-9)
  • ? – Anything after a question mark is optional.
To create the phone mask portrayed above you would do this in script:
You can also create your own definitions. ¬†In the examples below I have created some custom definitions to ensure specific characters are inputted in the correct positions (i.e., times must be prefixed with a 0 or 1. ¬†No other numbers will work). ¬†There is also a “completed” event which fires when all characters have been entered. ¬†If your mask contains optional characters that are ignored then that function will not fire. In that case you may need to use the textbox’s blur event, or better yet, both events.

I have used these masks in past projects:

Standard Time Textbox:

This mask ensures users enter a Standard Time into the textbox (i.e., 03:30PM). For the period (AM/PM) it is case insensitive and will also accept the first character (A or P) or neither (in which case it will assume AM).  It will upcase the period.

Zip Code Textbox:

This mask ensures users enter a 5-digit Zip Code or Zip+4.  If anything is partially entered the textbox will clear.
Remember when these values are retrieved server-side they will be in the format shown in the textbox.

See a DEMO.

Enjoy.

Read More

Hidden Accessible Fieldsets

It is good to group checkboxes and radio buttons for accessibility purposes.  The fieldset and legend elements allow developers to group related controls and labels.  Grouping elements make it easier for users to understand their purpose.  Screen readers will detect fieldsets and inform the user of their purpose via the legend tag.  Keep in mind that an elaborate interface may not transfer logically to someone using a screen reader.   With CSS you can cater to both worlds.  You can utilize fieldsets but also hide them if they are not visually pleasing.  A hidden fieldset is completely detectable by a screen reader.

Here is a snipplet of CSS that will hide the fieldset and remove the legend indent.
If you want to hide the legend as well then alter the CSS as so:
See a DEMO

Enjoy.

Read More