views:

442

answers:

2

Hello, I'm still kindof new to jQuery, so there probably is an easy solution, but I can't find anything. I've made this registration form, that checks if the username or email is taken as the user is typing in the username. Basically it just makes a json request that returns true or false depending on if the username / email is already taken.

The problem is, that now it makes a request on basically every keypress that the user makes while focused on the field if the input text is more than 3 characters long. For now, that works, but that's a lot of server requests. I'd like it to make a request only when the user has not typed for, say, a half second.

Any ideas on how I might be able to do that ?

$(document).ready(function() {
$("#user_username").keyup(function () {
 var ln = $(this).val().length;
 if (ln > 3) {
  $.getJSON("/validate/username/",
  {value:$(this).val()},
  function(data){
   if (data.reg == true) {
    $("#status-for-username").html("Username already in use");
   } else {
    $("#status-for-username").html("Username available");
   }
  });
 }
});
$("#user_email").keyup(function () {
 var ln = $(this).val().length;
 if (ln > 3) {
  $.getJSON("/validate/email/",
  {value:$(this).val()},
  function(data){
   if (data.reg == true) {
    $("#status-for-email").html("E-mail already in use");
   } else {
    $("#status-for-email").html("");
   }
  });
 }
});

});

A: 

You can use window.setTimeout and window.clearTimeout. Basically trigger a function to invoke in x milliseconds and if another keypress event is fired beforehand then you clear that handler and start a new one.

 //timeout var
 var timer;
 $('#username').keyUp( function(){
    //clear any existing timer
    window.clearTimeout( timer );
    //invoke check password function in 0.5 seconds
    timer = window.setTimeout( checkPasswordFunc, 500 );
 });

function checkPasswordFunc(){
  //ajax call goes here

}
redsquare
+2  A: 

For waiting an amount of time since the last keystroke, you could do something like the jQuery.typeWatch plugin does.

Here I post you a light implementation of the concept:

Usage:

$("#user_username").keyup(function () {
  typewatch(function () {
    // executed only 500 ms after the last keyup event.
  }, 500);

Implementation:

var typewatch = function(){
    var timer = 0;  // store the timer id
    return function(callback, ms){
        clearTimeout (timer);  // if the function is called before the timeout
        timer = setTimeout(callback, ms); // clear the timer and start it over
    }  
}();

StackOverflow uses the plugin I mention, for syntax coloring the code on edition.

CMS
Thanks, that's just what I was looking for.
gvidou
You're welcome!
CMS