Wednesday, 1 May 2013

HTML5 custom data attributes are case sensitive, and potentially confusing. Just stick to lower-case.

I have a form where the user can enter the hours that a business is
open, and with a pair of select boxes for each day of the week (ie,
"From" and "To" select box with times of the day)

Now I wanted to set this up so that the first time the user sees the
form, it already has default values of 9-5pm for Monday to Friday, and
10-4pm on Saturday and Sunday.

The model class we have has a variable called editMode() that
indicates whether the form is displaying an existing record or a new
record. I planned to use this to toggle the javascript code so it only
sets the values for "opening hours" if the record is not coming from
the database.

I was trying to access some data attributes I had set up as:

<div id="editModeStatus" data-isEditMode="${model.editMode}" ></div>

with jQuery code:

if (!$('#editModeStatus').data('isEditMode')) {
alert('editMode?' + $('#editModeStatus').data('iseditmode'));

And in the alert message, I would get:

editMode? undefined

and changing that code to:

alert('editMode?' + $('#editModeStatus').data('iseditmode'));

gave me

editMode? false

--when it should have been true, because that's the value that was
displaying in the HTML:

<div id="editModeStatus" data-iseditmode="false" ></div>

Googling on "data attribute case sensitive" brought me a couple of
posts discussing the case-sensitivity of html5 data attributes, and
how DATA ATTRIBUTES CAN ONLY BE LOWER-CASE UNLESS THERE IS A HYPHEN
PRECEDING THE UPPER-CASE CHARACTER

Not something I'm likely to remember immediately, so to simplify
things, I'd rather just use lower case in both the HTML and
Javascript.


REF:

http://blog.benpowell.co.uk/2012/03/warning-html5-data-attribute-is-case.html

1 comment:

Anonymous said...

Just to clear things up:

data-lowercase = data("lowercase")

data-camel-case" = data("camelCase") or data("camel-case")

The html5 spec dictates that attribute names cannot be case sensitive, so data-camelCase == data-camelcase. Jquery is just nice enough to give you another option that looks cleaner in the code.