I have one form field that requires unique code value. When user tries to enter new record or update existing record I have to check if this code already exist in Database. I came up with solution where I use on blur function to send Ajax call and then return true or false. If returns false that means that value already exist and user will be notified, if true they can save the record. Here is example of my function:
$('.check-code').on('blur',checkCode);
function checkCode(e) {
e.preventDefault();
var element = $(this).get(0), // Dom element
fldVal = $(this).val(), // Field value
isValid; // Flag variable.
if(!fldVal){
isValid = false
return;
}
$.ajax({
type: 'POST',
url: 'AjaxFunctions.cfc?method=checkCode',
data: {'fldVal':fldVal},
dataType: 'json'
}).done(function(obj){
if(obj.STATUS === 200){
if(obj.RESULT === true){
isValid = true;
element.setCustomValidity("");
}else{
isValid = false;
element.setCustomValidity(obj.MESSAGE);
}
}else{
$('#frm_message').show().addClass(obj.CLASS).html(obj.MESSAGE).delay(7000).fadeOut('slow').queue(function(){
$(this).removeClass(obj.CLASS).dequeue();
});
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert('Error: '+errorThrown);
});
}
//This function submits the form
$('.frm-Submit').on('submit', submitFrm);
function submitFrm(e){
e.preventDefault(); // Prevnts default form submit.
var frmID = formData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'AjaxFunctions.cfc?method=saveFrm',
data: formData,
dataType: 'json'
}).done(function(obj){
if(obj.STATUS === 200){
//Success.
}else{
//Failed.
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert('Error: '+errorThrown);
});
}
One problem that I found was if I click to edit existing record and I change the code. Then I click on Submit button and my on blur function is not triggered. So in this case user will submit duplicate code because on blur did not run before submit. I'm wondering if there is a way to prevent this behavior?