views:

94

answers:

2

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');
      }
});
A: 

Try this:

$("input#name").blur(function() 
{
  var name = $(this).val();
  if (name.length == 0)
  {
        // Testing
        alert('Empty');
  }
});

Edit: Nick pointed out that the input text needs to checked when the blur happens. If I make any more change, it will be just like his answer, so I stop here.

Khnle
This approach doesn't work...you're getting the value when the page loaded, not what it was when the element's `blur` event fired, you need to get the value at that time.
Nick Craver
+1  A: 

You want to use $(this).val(), like this:

$("input#name").blur(function() {
   if ($(this).val().length === 0) {
     // Testing
     alert('Empty');
   }
});

Currently you're checking if('input#name:empty') which is true, any string is going to be true in JavaScript (which is weakly typed). Also the :empty selector checks that it has no child elements, not that its value is empty, so check that the value is an empty string, or the .length is 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, #name will suffice and be faster, the input prefix is superfluous.

Nick Craver
Perfect, thanks Nick. if you have some time, could you explain this bit please: if ($(this).val().length === 0) {Thanks again!
Keith Donegan
@Keith - Certainly, `this` refers to that input DOM element inside any event handler like the function we're passing into [`.blur()`](http://api.jquery.com/blur/), wrapping it in [`$()`](http://api.jquery.com/jQuery/) gets the jQuery wrapped version of it, which lets you use [`.val()`](http://api.jquery.com/val/) to get its value. We're then checking if that string's length is greater than 0, meaning it has some characters in there.
Nick Craver