Non-existent HTML attributed input field

Is it good practice to bind a nonexistent attribute to an html element in order to use it in jquery. for example

<input type="text" valrule="someregexstring" />


then just use jquery to select all elements that contain the valrule attribute and parse the regex string.

Is this "no-go" as far as coding standards and best practices go?


source to share

4 answers

You must use a prefix data-<myAttribute>

. It is supported by HTML5, other browsers will ignore it and you can easily access it with jQuery using the .data()


<input  id="myInput" type="text" data-MySuperMassiveAttribute="Awesome"/>


and you can get information like this:

var howAmI = $('#myInput').data('MySuperMassiveAttribute');
alert(howAmI); // now everybody knows how awesome you are ;-)




Use the HTML5 data prefix for the new attribute like this:

<input type="text" data-valrule="someregexstring" />


Its valid HTML 5 ..



You definitely can. Although HTML5 introduced what is called data attributes, it allows you to set custom attributes on elements in a standard way.

You just prefix the attribute names data-

<input type="text" data-valrule="someregexstring" />


Although introduced in HTML5, you can still use it with HTML4 documents.

Using jQuery (1.4.3+), the data attributes can be accessed . data () - or via . attr () .



I didn't personally do that. Some browsers ignore "nonexistent" attributes when parsing HTML, so these attributes are not persisted to the browser's DOM page. When jQuery selectors are executed, they may not find this attribute.

If you are guaranteed to work in HTML5 compatible browsers, you can use the HTML5 prefix data-

for your attributes, eg.

<input type="text" data-valrule="someregexstring" />


However, this may not work if you are running older browsers. For example, it turns out that almost half of our customers are using IE7 without planning to upgrade (moving at government speed).



All Articles