Here is small little jquery plugin that checks if the element passed in is an input element and if it is empty:
$.fn.inputIsEmpty = function() {
if (!this.is('input:text')) {
return false;
} else {
return $.trim($(this).val()).length == 0;
}
};
The above logic works. So I tried turning this into a sweetened ternary expression:
$.fn.inputIsEmpty = function() {
this.is('input:text') ? $.trim($(this).val()).length == 0 : false;
};
But it just returns undefined - what am I doing wrong?
I would make use of operator short circuiting:
return this.is('input:text') && $.trim(this.val()).length === 0;
If this.is('input:text')
is false
, the second part won't need to be evaluated, as false && any boolean
will be false
regardless of the other boolean's value. It acts like your if
statement.