Reputation: 1514
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.
Upvotes: 3
Views: 12097
Reputation: 6561
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
}
Upvotes: 2
Reputation: 207501
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) {
Upvotes: 9
Reputation: 1341
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.
Upvotes: 2