For some reason, I cannot figure out how to return the value of an input after I’ve typed something into it. This is in relation to this problem and I’m not able to validate anything without the username value being recognized. I’m running jQuery 1.6.1 and Validate 1.8.1.
Here’s the form HTML:
<form class="cmxform" action="register.php" method="post" name="signup" id="signup">
<ul>
<li>
<label for="username">Username: <em>*</em></label>
<input type="text" id="username" name="Username" size="20" class="required" placeholder="Username" />
</li>
</ul>
</form>
Before submitting the form, I want to make sure I can see the value of the username I type into the input. I have an alert that returns the value of the username, but the alert always shows nothing. Here’s the JS code I’m using:
$(document).ready(function(){
var username = $("#username").val();
var parameter = "action=checkusername&username="+username;
$.validator.addMethod("checkAvailability",function(value,element){
$.ajax({
url: "dbquery.php",
type: "POST",
async: false,
data: parameter,
success: function(output) {
alert (username);
return true;
}
});
},"Sorry, this user name is not available");
// jQuery Validation script
$("#signup").validate( {
rules: {
Username: {
required: true,
minlength: 5,
checkAvailability: true // remote check for duplicate username
}
}
},
messages: {
Username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
Should I be using something other than val() to get the value of the username? I’m so confused why it’s not giving me the value that I need!
you are hard coding username at the beginning of your javascript. do it inside the addMethod success call
HTML
putting it where you have it now means that when the page loads it immediately grabs the value in the username text field, which will be empty.
EDIT:
changed the code a little to work correctly
EDIT: jsfiddle of above code