I have an input that I want to validate:
<input type="text" id="input" />
And here’s the JS:
jQuery("#input").live('change', function() {
if("#input:not(:empty)") {
alert('not empty');
}
else if("#input:empty") {
alert('empty');
}
});
Even when the “#input” is empty there’s no way of displaying alert with “empty” message. So, basically, no matter what I do, only the first statement is true and the second is false, always.
What’s wrong?
JQuery’s :empty selector selects all elements on the page that are empty in the sense that they have no child elements, including text nodes, not all inputs that have no text in them.
Jquery: How to check if an input element has not been filled in.
Here’s the code stolen from the above thread:
This works because an empty string in JavaScript is a ‘falsy value’, which basically means if you try to use it as a boolean value it will always evaluate to
false. If you want, you can change the conditional to$(this).val() === ''for added clarity. 😀