Jamie Kitson
Jamie Kitson

Reputation: 4140

How to add data to HTML for javascript to use

I have a dynamically created page with repeated elements, like so:

<input type="file" name="file1">
<input type="file" name="file2">
<input type="file" name="file3">

I would like to add some data to each of these elements for use in JavaScript. Originally I used "spare" attributes that while valid on an input tag were not valid on a file type input tag, eg, size. I have now added it to the class attribute, but have to use a regex to get it out again. Neither of these methods seem very satisfactory, is there a better way?

Upvotes: 0

Views: 71

Answers (4)

Harshal Patil
Harshal Patil

Reputation: 6759

with attribute start with data- you can use your own other name appending to it.

Go through this examples

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116100

Quite often I see data added through attributes that are prefixed with data-, for instance:

<input type="file" name="file1" data-filesize="871">

jQuery even has function to conveniently read that information, for instance like this:

var filesize = $('input[name="file1"]').data('filesize');

And, to write the data, attr can be used:

$('input[name="file1"]').attr("data-filesize", filesize );

See also: HTML 5 data atributes

Upvotes: 4

devqon
devqon

Reputation: 13997

Use the data attribute: <input data-something="somevalue" />

Upvotes: 1

Maurice Perry
Maurice Perry

Reputation: 32831

You can use attributes with a name starting with "data-"

Upvotes: 1

Related Questions