I have the code below that validates a form field called lms_domain. It simply checks whether the subdomain selected by the user is available using an AJAX call to another file that executes a MySQLi count query. The code currently works on submission of the form but I would like it to execute the AJAX post when the user types into the field, or has completed the field. How do you achieve this using JQuery?
$('#lms_name').keyup(function(){
/* some code here */
$.ajax({
type: 'POST',
url: 'assets/lmsdomaincheck.php',
data: "lmsdomain="+value+".thedomain.com",
async: false,
success: function(htmldata){
if (htmldata=="success") {
$('#spanlmsdomain').html('GOOD');
}else {
msg+="<b>Error on LMS domain name : </b>"+value+".thedomain.com not available.<br/>";
$('#spanlmsdomain').html('BAD');
}
}
});
/* some code here */
});
Thanks in advance for any tips!
$('#lms_name').on('blur', function() {
This will execute once the cursor leaves the field, indicating completion of the user input.
var busy = false;
$('#lms_name').on('blur keyup keypress', function(e) {
if ((e.type == 'keyup' || e.type == 'keypress') && busy === false) {
busy = true;
var avail = setTimeout(function() {
$.ajax({ ...yourAJAXhere... });
busy = false; // Put this line in the success() / error() callbacks
}, 500);
} else if (busy === false) {
clearTimeout(avail);
busy = true;
$.ajax({ ...yourAJAXhere... });
busy = false; // Put this line in the success() / error() callbacks
} else {
return;
}
});
This will combine the first one with a timeout that waits .5 seconds and then checks the server for availability. It makes sure only one check goes at a time but is a quick mock up so you would want to fine-tune for your situation.
Well you already are using that function, what I would have added here would have been a number of character count. Such as
if(document.getElementById("lms_name").length > 5) {
/* execute the ajax here */
}
Because most users want the username of 5 - 8 letters. So this would be enough to check for the username when the user has added 5 letters to the textarea or input.
$('#lms_name').blur(function(){
if ($(this).data('tOut')) {
clearTimeout($(this).data('tOut'));
}
var newTOut = setTimeout(function () {
// ajax call here
}, 10000);
$(this).data('tOut', newTOut);
});
Trigger a timeout when there's a good amount of delay after the last change to the field was made & the focus shifted off the field.