tags:

views:

66

answers:

4

I'm using this Jquery function for available username check.

How can I fire this Jquery function only if the username field is greater of 5 characters?

Jquery looks like:

$(document).ready(function() {
$('#usernameLoading').hide();
$('#username').blur(function(){
$('#usernameLoading').show();

$.post("usercheck.php", {
un: $('#username').val()
}, function(response){
$('#usernameResult').fadeOut();
setTimeout("finishAjax('usernameResult', '"+escape(response)+"')", 400);
});
return false;
});
});

function finishAjax(id, response) {
$('#usernameLoading').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
} //finishAjax

Can I use something like this and how:

var usr = $("#username").val();
if(usr.length >= 5)
{   
}
A: 

Pretty close, it should work like that:

if($("#username")[0].value.length >= 5) {

// do something

}

ntziolis
A: 
$('#username').keypress(function(){

  var name = $(this).val();
  if (name.length > 5) doAjaxCheck(name);


});

I split the doAjaxCheck into a seperate function becuase you may want to check it again becuase of clipboard operations etc.

James Westgate
A: 

Should be able to. Just put it in under $('#username').blur(function(){ and wrap the current block in the if statement

Josh
+2  A: 
$(document).ready(function() {

    $('#usernameLoading').hide();

    $('#username').blur(function(){

        if ($("#username").val().length < 5) {
            return;
        }

        $('#usernameLoading').show();
        $.post("usercheck.php", {
            un: $('#username').val()
        }, function(response){
            $('#usernameResult').fadeOut();
            setTimeout("finishAjax('usernameResult', '"+escape(response)+"')", 400);
        });
        return false;
    });
});

function finishAjax(id, response) {
   $('#usernameLoading').hide();
   $('#'+id).html(unescape(response));
   $('#'+id).fadeIn();
} //finishAjax
Ken Browning
Thanks Ken. Your answer helped me a lot.
Sergio