Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.data() conditional statement

I'm using the html5 "data" attribute on a element, and I want to assign the attribute value to a variable only if it exists and if it's not empty:

var xxx = $(this).data('what') ? $(this).data('what') : 'default_value';

but it doesn't work. I always get the default value...

like image 815
Alex Avatar asked Dec 27 '22 21:12

Alex


2 Answers

Using a short circuit is simpler and more efficient:

var xxx = $(this).data('what') || 'default_value';

But your code should have worked anyway, assuming the data existed (as the commenter noted).

like image 169
Jamie Treworgy Avatar answered Jan 12 '23 20:01

Jamie Treworgy


Looks like $(this) is not what you expect it to be. Other than that, the statement looks fine. Demo

like image 37
amit_g Avatar answered Jan 12 '23 21:01

amit_g