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?
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');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With