Currently, I’m adapting a registration page to use Ajax/jQuery. Its in the simple stage, asking simply for a username and password.
I want to use jQuery to tell the user if the current entry in the username textbox is invalid or has already been taken. If either conditional is met, the div namemsg will have text added to it and execute the fadeIn event.
The page loads with he submit button disabled, and upon passing validation the button is enabled. To do this, I have the following ajax request to handle the username validation
$("#username").keyup(function(){
//get current value
thisVal = $(this).val();
//execute request to see if current val exists in database
$.ajax({
type: "GET",
url: "includes/phpscripts.php?action=checkUser",
data: {username:thisVal},
success: function(data){
//if username is already taken, show warning and disable submit button
if (data == 'true'){
$("#namemsg").text("Username is already taken");
$("#namemsg").fadeIn(100);
$("#submit").attr('disabled', 'disabled');
}
//otherwise, possible valid username
else if (data == 'false'){
//check if username is of the proper length. If not, display
//error and disable submit button
if ($(this).val().length < 5){
$("#namemsg").text("Invalid Username");
$("#namemsg").fadeIn(100);
$("#submit").attr('disabled', 'disabled');
}
//valid username, enable submit button and hide any error messages
else {
$("#namemsg").hide();
$("#submit").removeAttr("disabled");
}
}
}
});
return false;
});
My issue is that the request gets the propper value from the server, but firebug complains that elem.nodeName is undefined at line 2368 of jquery 1.7.2. That line is
if ( elem ) {
hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
When I set the breakpoint at if (elem), elem had the values
nodeName : INPUT
type : text
and hooks returned undefined. Is this a Firefox specific issue, an issue with my code or jQuery? Also, Is there a workaround for this?
Inside your
successhandler,thisis the jqXHR request, not the$("#username")field, so$(this).val()is erroring.As you’ve got the value cached, it’d be best to use
thisValinstead of$(this).val(), but in general the way to fix this is to set thecontextoption to the element;You can see the docs for this method on the
jQuery.ajax()page (search for “context”).And another way you’ll see is to set the
thisthat pointed to the element to another variable;