views:

43

answers:

1

I'm checkin a form for empty values via the following method


      $("#reservationForm").find("input[type=email], input[type=tel], input[type=text]").filter(function(){
       if($(this).val() == ""){
        $(this).css("border","solid 1px red").after('Please fill in your '+this.id+'');
        f.preventDefault();
       }

Now i want to improve the usability and set the focus to the first empty field, but that's the problem. I tried all of the following, but everytime only the last empty field gets the focus


        $(this).eq(0).focus();
        $(this:first).focus();
        $(this:first-child).focus();

How can i set the focus automatically to the first empty field?

A: 

You need to place it at the end, after the .filter() overall, like this:

$("#reservationForm").find("input[type=email], input[type=tel], input[type=text]").filter(function(){
  if($(this).val() == ""){
     $(this).css("border","solid 1px red").after('Please fill in your '+this.id+'');
     f.preventDefault();
     return true;
  }
}).first().focus();

This way you're getting the .first() of the elements that match the filter. The return true is important because only those elements that are empty are left in the set after the .filter() is called...currently you're using it as more of a .each() call.

The reason it's currently setting it to the last is this is each element as you iterate through, so it's focusing all of them, and whichever runs last is the one left with the focus...instead you want to get the set of empty and focus the first of those elements.

Nick Craver