1

I have the following HTML:

<a href="#" data-secID="1901">
  <img src="pencil.png" title="Edit" />
</a>

And the following jQuery that I expect to alert the secID of 1901 to the screen, but instead alerts 'undefined' to the screen.

$(document).on("click", "a[data-secID]", function ($e) {
  alert($(this).data('secID'));
  $e.preventDefault();
});

Why am I get 'undefined' instead of 1901?

2 Answers 2

3

It appears as though the attribute name is converted to lowercase. Try this:

$(document).on("click", "a[data-secID]", function ($e) {
  alert($(this).data('secid'));
  $e.preventDefault();
});

Demo: http://jsfiddle.net/72Ykj/

Reference from comments: http://www.w3.org/html/wg/drafts/html/master/dom.html#embedding-custom-non-visible-data-with-the-data-%2A-attributes

Sign up to request clarification or add additional context in comments.

6 Comments

Wow... that's insane! Since when was case-sensitivity even a consideration with anything jQuery related? Anyway, thanks a ton for the answer. I never would have found this. I'll mark this as correct in about 10 minutes (or whenever SO lets me).
I don't know, i skimmed through the documentation and didn't see anything related to the case of the keys.
Just out of curiosity - how did you figure out that it requires all lowercase to find the data-secID attribute value?
From the docu "3.2.3.9 Embedding custom non-visible data with the data-* attributes - A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no uppercase ASCII letters." - w3.org
@kevin, you nailed it! w3.org/html/wg/drafts/html/master/… section 2.4.3 specifies that the attribute key is to be case insensitive..
|
0

[Edited after comments] A (not so good) workaround is to use

.attr('data-secID')

instead of

.data('secID)

2 Comments

Even with that edit, that doesn't answer his question. He likely wants to use data for a reason. Yes it is a work-around and does work, but it doesn't answer his question. Read the full documentation on data and it will show you why it's useful beyond the similarities to attr.
@EliGassert good shot and thanks for the correction, i'll precise this is a workaround in my answer : stackoverflow.com/questions/9444679/jquery-data-vs-attrdata

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.