2

I want to be able to add an attribute to a HTML element to be able to identify what its referring to.

E.g if I have a list of names and a checkbox next to each name, like this:

<div id="users">
 Bob smith <input type=checkbox />
</div>

And when a checkbox is clicked and the event handler function for it is called, I want to be able to identify which user was selected/unselected.

Ideally I'm looking for something like this:

<input type=checkbox data-userId = "xxx" />

Then when its clicked:

function handleClick()
{
  var userId = $(this).attr('data-userId');
}

However I'm looking to do this in a way that won't break my HTML validation, and would still be valid HTML and work in all browsers.

Any suggestions?

Ali
  • 261,656
  • 265
  • 575
  • 769

2 Answers2

6

Data attributes are provided by html5 and are valid attributes. You can access data attributes by data method by jquery

var userId = $(this).data('userId');
Adil
  • 146,340
  • 25
  • 209
  • 204
5

Adding data- attributes to your dom elements and then reading them with

var userId = $(this).attr('data-userId');

or even

var userId = $(this).data('userId');

IS the correct way to do this, and will not break any HTML validation.

Just note that there will be some case manipulation performed by jQuery on your data- attribute, as described here. To keep things simple, consider changing data-userId to data-userid

Community
  • 1
  • 1
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393