I have a simple form that I want to validate using blur if the text field is empty.
The below code should work, but keeps alerting me even if I pop in some text, please, what am I doing wrong?
var name = $("input#name").val();
$("input#name").blur(function()
{
if (('input#name:empty'))
{
// Testing
alert('Empty');
}
});
You want to use
$(this).val(), like this:Currently you’re checking
if('input#name:empty')which is true, any string is going to betruein JavaScript (which is weakly typed). Also the:emptyselector checks that it has no child elements, not that its value is empty, so check that the value is an empty string, or the.lengthis empty like I have above 🙂Also, unless there is the possibility of this ID being on another element type you don’t want to match,
#namewill suffice and be faster, theinputprefix is superfluous.