3e8.org

In EBCDIC we trust.

December 13, 2011

jQuery and HTML5 data attribute conversion

In jQuery 1.4.3 and later, you can use .data() to access the value of custom data attributes on your HTML5 elements. jQuery tries to figure out what type of data you're passing and do the appropriate result conversion, falling back to string if it can't figure it out. This is convenient, but a problem can occur when you want to pass a string but your value looks like (for example) a boolean:

<input id='abc' data-foo='true'>

$('#abc').data('foo')  /* true (boolean) */

It's not possible to quote the string value either; you'll just get a string with embedded quotes. The official workaround is to use .attr('data-foo'), which will return the raw string. Of course, this means that to safely pass a string without interpretation, you can't accept any other object. Some people are unhappy with this behavior, but... wontfix.

However, there's another trick you can use. Pass a quoted string inside a 1-element array, then reference that element. This will ensure the JSON parser is engaged because the value starts with [. It also lets you pass arbitrary objects you do want converted (in which case you couldn't use .attr()). Example:

<input id="abc" data-foo='["true"]' data-bar='[true]'>

$('#abc').data('foo')[0] /* "true" (string) */
$('#abc').data('bar')[0] /* true   (boolean) */

It's a little clunky, but at least you'll get consistent results. If you're passing several values, it's probably easier just to use a JSON hash.