In a nutshell a data attribute can be attached to the element that is described by
the attribute where areas the hidden input can't be inside another DOM element
and its use is limited to forms (In good practices anyway).
The hidden input is an actual DOM element while the data attribute is well... that an attribute, so it can be bound to a DOM element. That for the most part it but if you need
more info and maybe an example keep reading, I warn you it's kinda long and english is not my native language.
Basically the data attribute was created to add extra information to DOM elements, that can't be otherwise attached to it with the existing attributes such as class or the good old id.
This affects mostly web based apps or more specifically Saas', for which the need of data driven attributes is far more extensive than a regular website(even with a CMS behind it).
I used to day dream about this attribute many years ago, when you only had 2 choices:
- Use the html attributes for something that they we're not
originally created or designed
- Use the html attributes with tokens in them, to decode them
with client-side or a server-side function (split,splice,explode)
The problem with this approach is that no matter how you look at it, you are not
using the html attributes they way they're meant and designed to be used.
Html is a markup language so it doesn't naturally have data driven attributes
that you can't work with to manipulate data processing and behavior.
The basic scenario that I had then is that I wanted to have a single
jQuery Dialog to load all the data entry forms (clients,products,suppliers,etc)
Each form with different width and height. That way the client-side script would
be much smaller and I would need to add a new dialog for every new form that was
added to the app requested by the client.
This is how I used to do it before the data attribute came along:
Click to add a new product
Within the id token I had 3 values:
- The form to be loaded from the server
- The width of the dialog window
- The height of the dialog window
Other approach would be to use the href attribute but this is far worse than using the id
simply because the href attribute is meant to point to a DOM element or another source, not to hold any data to be processed.
Either approach involves breaking down the token using split or a similar function.
This how I do it now with the awesome data attribute:
Click to add a new product
This way I do not need a token, I can just get each attribute's value
with a good old $(this).attr('data-form');, $(this).attr('data-dwith'); and so on.
IMHO I think it's better to add a little extra data to the html elements than creating
a much longer javascript file thus heavier and more complex.