Hidden inputs vs HTML5 data attributes

18,537

Solution 1

One of the main drawbacks is accessibility.

Since those attributes aren't submitted to the server in POSTs, you'll need to keep in mind what happens in JavaScript-disabled browsers. If your page should also be able to degrade gracefully and perform those same AJAX-requested features via traditional form submissions if necessary, a hidden field will still be required.

That said, I'm a big fan of data- attributes when they make sense, especially in strictly "application" type sites where you can safely mandate JavaScript. It's a lot nicer to tag a table row with a data-id attribute than stuff a hidden field in one of its cells, for example. Especially coupled with jQuery's nice data- attribute support for the .data() method, that makes for clean, intuitive code in situations where hidden fields can be a bit messy.

Solution 2

Here's my take:

  • Hidden inputs are meant to be used in forms as a way of passing data back to the server without making it visible, or editable, on the page.
  • Attributes are meant to describe a property of an element. data- attributes are meant to convey information about an element to JavaScript on the page.

Based on that, a data- attribute on the html or body element would seem most appropriate.

An alternative, albeit less-semantic, solution is to serialize your page metadata as JSON and use a script tag to set it as global variable on the page. You can see this in action on, for instance, GitHub repositories, where a global GitHub object is created near the top of the page and some information (the repo name, the current branch, the latest commit) is added to it for easy access.

Solution 3

I know it's been a while since this post has been active, but I recently came across the topic, and I wanted to comment on the performance aspect of the two.

As others pointed out, Data attributes are for storing data in the DOM itself, and prior to HTML5 there were different ways to get around that need by using hidden inputs nested in DOM or by using other attributes.

hidden inputs are more performance intensive (especially when you scale them up) because they are DOM objects with many other attributes (taking up more memory).

using other attributes is more memory efficient compared to hidden inputs, but can require more processing. You probably need to prefix them with something and extract data using those prefixes. In addition, setting them and getting them can also be tricky and may mess up default functionality of some elements.

So here is set of guidelines I set for myself when it comes to choosing between hidden inputs and data attributes.

  • Choose data attributes when data is only intended for front end functionality (no need for submitting back)
  • Choose data attributes when there is large scale data that you need to store (example: graph coordinate, large listings with multiple parameters)
  • Choose hidden inputs when storing large chunks of data or data with special characters

Solution 4

Because data attributes are new, I don't think there is a real consensus yet about when they are appropriate or what best practices are. My personal feeling if that they make a lot of sense when you are attaching data to DOM elements further down in the page because they logically go along with those DOM elements. When you are looking at using them on the body tag I wonder why you are not keeping those values in regular javascript variables. I suspect that you would have better performance using regular javascript variables. All of these variables would be easily viewed in Firebug, etc. so its unlikely that one is more or less secure in that sense.

Regarding the initial page state, it sounds like you could probably put the javascript variable directly into the page instead of into a hidden field with the way you are using it. If you were posting a form to the server, the hidden element could be useful there, that is what hidden elements were designed for.

Its a good open question as to what best practices are on this.

Solution 5

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:

  1. Use the html attributes for something that they we're not
    originally created or designed
  2. 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:

  1. The form to be loaded from the server
  2. The width of the dialog window
  3. 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.

Share:
18,537

Related videos on Youtube

Alastair Pitts
Author by

Alastair Pitts

Developer. Engineer. Enthusiast. Goodjer. Bugler.

Updated on October 09, 2020

Comments

  • Alastair Pitts
    Alastair Pitts over 3 years

    Something that's been bugging me recently is the use of HTML5 data attributes and when is the appropriate to use them.

    Typically, on a page that performs a number of AJAX calls to my server, I require the ID that is representative of the page being viewed. I've currently been storing this in a hidden <input> element on the page, which is then accessed and stored in a JS variable at the top of my jQuery doc ready call.

    I've been considering moving it to a data-id attribute on the body element, which I then would access in jQuery using $('body').data('id');.

    Is there any advantages to using HTML5 data atttributes or visa versa? Performance? Security? "Best-Practices"?

    It's my understanding that data attributes are accessible by all browsers so dealing with IE isn't a concern.

    • elwyn
      elwyn about 13 years
      For this case, why don't you write the ID as a regular ID attribute?
    • Alastair Pitts
      Alastair Pitts about 13 years
      @elwyn: I have no idea. That never really occurred to me.
  • Alastair Pitts
    Alastair Pitts about 13 years
    The Id is already in the URL. Reliably getting it out of the URL is something that I'm struggling to do. This is because of the way my current Routes are set up. they are currently {controller}/{id}/{action}. I'm trying to fix this, but it's a whole other issue.
  • mcgrailm
    mcgrailm about 13 years
    I've used both javascript and php to extract id's a good regex can sometimes help too
  • Alastair Pitts
    Alastair Pitts about 13 years
    I never thought to use a regex. Thanks for the idea!
  • sports
    sports about 11 years
    what if the values of the data-* attributes in the body are sent from the server? you can't know them a priori to make them javascript variables.
  • Jarrett Widman
    Jarrett Widman about 11 years
    Seeing as this answer is 2 years old, I think there is more of a consensus on how these are used and yes I think having data-* attributes is fine on the body tag or anywhere else for that matter.