Reputation: 9365
I'm assigning a javascript variable with a value as
var newline = $("#newline").val();
The $("#newline").val()
may or may not exist (in some cases, the #newline
may not exist in the DOM, or even if it exists, it may not have any value).
I want to check whether the var newline
is set or not. How do I do that?
Upvotes: 2
Views: 435
Reputation: 15867
jQuery:
(function() {
if (this && this[0] && this[0].value) {
// Has a value
} else {
// Has no value
}
}).call($("#newline"));
this[0]
is the HTML Element itself, rather than a jQuery Object.
Pure JavaScript:
(function() {
if (this && this.value) {
// Has a value
} else {
// Has no value
}
}).call(document.getElementById("newline"));
Upvotes: 0
Reputation: 943591
This comes down to "What does the jQuery val
method return if there are no elements matching the selector in the DOM?"
The answer to that is undefined
so:
if ( typeof newline === "undefined" ) {
}
Upvotes: 5