How to add attributes to a HTML element in a valid way?

Posted by Click Upvote on Stack Overflow See other posts from Stack Overflow or by Click Upvote
Published on 2012-12-04T05:01:05Z Indexed on 2012/12/04 5:03 UTC
Read the original article Hit count: 133

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery