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?
To check if the input text box is empty using jQuery, you can use the . val() method. It returns the value of a form element and undefined on an empty collection.
version added: 1.7jQuery. The $. isNumeric() method checks whether its argument represents a numeric value. If so, it returns true . Otherwise it returns false .
jQuery empty() MethodThe empty() method removes all child nodes and content from the selected elements. Note: This method does not remove the element itself, or its attributes. Tip: To remove the elements without removing data and events, use the detach() method.
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:
$('#apply-form input').blur(function() //whenever you click off an input element
{
if( !$(this).val() ) { //if it is blank.
alert('empty');
}
});
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. :D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With