How can I check in jQuery if an input is empty ?
I tried:
$('#location').keydown(function(event) {
if($("#location").val().length == 0 ) { $("#finalSearch").attr('disabled', 'true'); }
if($("#location").val().length != 0 ) { $("#finalSearch").removeAttr('disabled'); }
});
But, I want the alert pop even if there’s nothing in my field.
What I want to do:
-
There’s nothing: error message.
-
There’s one letter: no error message.
-
I remove this letter: error message.
-
If the field is populate but another function: no error message.
Thanks for help.
You should use the
keyupevent rather thankeydown– on key down the field hasn’t updated yet so testing thevalueat that point doesn’t give you the right result.It wouldn’t hurt to do the same test on
blurtoo, to allow for if the user changed the field via the Edit menu or drag’n’drop or whatever.Also, unless using a really old version of jQuery use the
.prop()method rather than.attr()to set the disabled state: