2

Hi I was wondering if someone could give me a hand with how exactly data-* works... I need to create a custom attribute which will be accessed with jquery...

heres what i got so far:

HTML

<select name='province' class='province' data-IsSelectSingle='true'> ... etc ...

jQuery

if($.data("IsSelectSingle") != "true")

and even though its true it executes still... ive also tried...

if($.data($(".province"), "IsSelectSingle") != "true")

Figured I'd try that since thats what it shows as the method on the jquery site but it doesn't seem to work either... any ideas why this might be?

Thanks in advance!

2 Answers 2

5

You need to grab the element via its selector (.province), and then use .attr or .data to get the data:

$(".province").attr("data-IsSelectSingle") != "true"

or

$(".province").data("IsSelectSingle") != "true"

Note, there are major differences between .attr and .data, and they way they handle HTML5 data attributes. See the docs for reference (.attr & .data).

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

3 Comments

hmm it seems to have worked using $(".province").attr("data-IsSelectSingle") != "true" but not with .data I'm gonna read up on .data a bit more none the less but your first solution definately worked thanks a bunch!!
Absolutely. :) Happy to help. And see that documentation... that use of .data should work for the data attribute. If it's not, there might be something else at play.
Actually, in more recent experience, I discovered what I believe has always been true about the .data method: it kind of "evals" the value of the attribute. So, for the above to work, @Lord-Link, you'd have to != true (or better yet, !== true), instead of quoting "true".
1

You need a selector for the data for it to know where to look for the data attribute.

if($("select.province").data("IsSelectSingle")!="true")

Comments

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.