Question

A very general question.

I am dynamically generating a form that is split into multiple levels of tabs using HTML / JavaScript.

I want to highlight some of the fields (those that have a value differing from a global template) with a star * symbol using CSS and background-image.

A JS field iterates through each field, compares its value, and sets a CSS class for it if necessary. So far, so good.

Now in addition, I want not only every changed field to be marked with a star, but also the tab it is in.

Because I love it simple, I would like to store the element ID of the tab as an attribute somewhere in each field's HTML tag (something like "parentTab"). The JS function then highlights the field and its "parentTab" element (and maybe that one's "parentTab" as well).

My first approach is to misuse the "title" attribute or somethiong to store parentTab in. Of course, that's dirty. However, if I just wildly add arbitrary attributes to the DIV or INPUT tag, it won't validate any more and I feel less than secure accessing these attributes - who knows how different browsers handle it, and will handle it in the future?

So my question is: Is there a valid, standards compliant way - an attribute of some sort - to store arbitrary data inside HTML tags, for further processing by JavaScript?

Of course, I could create a "parentTabs" JS array and be done with it. But storing it in the input itself would be so much more elegant.

Was it helpful?

Solution

You could find out which tabbed element a field belongs to by writing an isChildOf function, like this: http://jimkeller.blogspot.com/2008/07/jquery-ischildof-is-element-child-of.html

Using the DOM to work this out will always be more "elegant" than duplicating the data in some custom format.

OTHER TIPS

with the introduction of html5, you can use attributes that start with data-, and they'll still validate.

<input type="text" name="username" data-parentTab="tab1" value="non-default">

The rel attribute is often a great valid choice for storing data like this.

In jQuery you have the Data API for the matter. http://docs.jquery.com/Internals/jQuery.data

If you do not use jQuery, you can add your own tags and store anything in it. everybody will tell you this is not nice etc, but all the great web firms are doing so. so you will end up in a great company ;-)

I like how John Resig did this: a script tag with arbitrary type. His example is about templating, but you could really use this for anything.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top