3

i am quite new to jquery. i am trying to check on page load if data attribute has a value or is that empty. here is my html

data-tablet="img/xl.jpg"

How i wanna check if there is a path set or is it empty. here is my js

if ($('#myImg').data('tablet')=null) {
alert('Path not Set');
};

But it's giving me an error. can you please tell me how to resolve it. thanks.

3
  • 7
    = is assignment, == is equality and === is identity Commented Nov 24, 2014 at 13:45
  • 1
    As @blgt says, it's likely to be an issue with your syntax. It would be useful if you specify in your question what error you're actually seeing however. Commented Nov 24, 2014 at 13:45
  • possible duplicate of Can't make multiple if conditions in JavaScript? Commented Nov 24, 2014 at 14:08

3 Answers 3

9

First as pointed out in comments, you are missing an equal sign so you are not doing a comparison. Second issue is that if there is no data attribute it is undefined, not null.

if ($('#myImg').data('tablet')===undefined) {
Sign up to request clarification or add additional context in comments.

Comments

2

You could use this.

if (!$('#myImg').data('tablet')) {
  alert('Path not Set');
};

In Javascript every object is convertible to a boolean, so if it's null or an empty string it'll be false, otherwise it'll be true.

2 Comments

not working.If i omit the data attrabute how can i check if it's there or not?
If the data attribute doesn't exist then the JQuery data call will return undefined, if the attribute exists but it's blank then JQuery will return an empty string. Both of those evaluate to false, so the exclamation mark at the beginning says to take the opposite of that, which is true, therefore you'll get the alert if the data-tablet attribute is either blank or doesn't exist.
2

You can check whether data attribute have data or exist by using the following code in jquery.

In the beginning, there was typeof. This handy operator gives you the "type" of a javascript value

if(typeof $('#myImg').data('tablet') != 'undefined') {
  // data exist
} else {
  // data not exist or undefined
}

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.