The usual way to check if the value of a property is the special value undefined
, is:
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
To check if an object does not actually have such a property, and will therefore return undefined
by default when you try and access it:
if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
To check if the value associated with an identifier is the special value undefined
, or if that identifier has not been declared. Note: this method is the only way of referring to an undeclared (note: different from having a value of undefined
) identifier without an early error:
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined
might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.
However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.
If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined
value itself:
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0
means false
, everything else true
. So you could write:
if ($(selector).length)
You don't need that >0
part.
Best Answer
UPDATED for clarification and example
examples: http://jsfiddle.net/pxfunc/5kpeJ/
Method 1.
input
eventIn modern browsers use the
input
event. This event will fire when the user is typing into a text field, pasting, undoing, basically anytime the value changed from one value to another.In jQuery do that like this
starting with jQuery 1.7, replace
bind
withon
:Method 2.
keyup
eventFor older browsers use the
keyup
event (this will fire once a key on the keyboard has been released, this event can give a sort of false positive because when "w" is released the input value is changed and thekeyup
event fires, but also when the "shift" key is released thekeyup
event fires but no change has been made to the input.). Also this method doesn't fire if the user right-clicks and pastes from the context menu:Method 3. Timer (
setInterval
orsetTimeout
)To get around the limitations of
keyup
you can set a timer to periodically check the value of the input to determine a change in value. You can usesetInterval
orsetTimeout
to do this timer check. See the marked answer on this SO question: jQuery textbox change event or see the fiddle for a working example usingfocus
andblur
events to start and stop the timer for a specific input field