Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing arbitrary info in HTML tags for JavaScript?

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.

like image 612
Pekka Avatar asked Nov 27 '22 19:11

Pekka


1 Answers

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">
like image 147
peirix Avatar answered Dec 17 '22 13:12

peirix