Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 921
Ali Avatar asked Jan 23 '26 11:01

Ali


2 Answers

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');
like image 58
Adil Avatar answered Jan 25 '26 06:01

Adil


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

like image 28
Adam Rackis Avatar answered Jan 25 '26 05:01

Adam Rackis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!