7

I have a basic login form, which uses ajax to login users. If the details are incorrect text is displayed showing login has failed. When this is shown the last textbox the user entered text in loses focus.

Is it possible to set focus to the last textbox which the user was on before pressing submit/pressing enter?

$('#login').click(function (e) 
 { 
  e.preventDefault();
  $.ajax({
  type: "POST",
  dataType: "text",
  url: "login.php",
  data: "username=" + $("#username").val() + "&password=" + $("#password").val(),
  cache: false,
  success: function(reply)
  {
   if (reply.indexOf("Success") >= 0)
   {
    location.reload();
   }
   else
   {
    $("#loginResult").html("Login Failed");
    //set focus here       
   }
  }
 }); 

Any suggestions, Thanks.

Elliott
  • 3,812
  • 24
  • 69
  • 93

1 Answers1

8

Subscribe all of your inputs to the focusout event

$('.input').focusout(function () {
   $('#myform').data('lastSelected', $(this));
});
Vadim
  • 17,897
  • 4
  • 38
  • 62
  • 2
    personal taste: i would attach the $(this) to the form, as in, $('#myForm').data('lastSelected', $(this)). it feels less polluting that global variables – davin Jan 16 '11 at 19:20
  • @davin, if you have multiple forms in the page you will need to keep a reference to the form as well .. – Gabriele Petrioli Jan 16 '11 at 19:22
  • @Gaby, if you have multiple forms and use a global variable you will end up focussing elements in the _wrong_ form! – davin Jan 16 '11 at 19:25
  • Thanks, where about am I placing this as I get ther error : $(".input").focusout is not a function – Elliott Jan 17 '11 at 00:21
  • @Elliott, not sure, wherever your click handler goes. See the documentation here http://api.jquery.com/focusout/ – Vadim Jan 17 '11 at 03:27