I previously asked how can I simplify a validation process:
How can I simplify this JQuery validation process?
But in hindsight, what I really meant to ask was how can I turn that process into a reusable function.
I'm going through some old code that I wrote, and I am trying to clean it up so there's not a lot of redundant code.
I have many onClick
events that look like this:
$('#addSubmit').on('click', function(){
var addcriteria = {
addcity: $('#addcity').val(),
addregion: $('#addregion').val(),
addloctype: $('#addloctype').val(),
// several more values
}
if(addcriteria.addcity == "" || addcriteria.addcity == null){
$('#errorModal').modal('show');
$('.message').text('You must enter a City.');
$('#errorModal').on('hidden.bs.modal', function(){
document.forms["addEquipForm"].addcriteria.addcity.focus();
});
return false;
}
if(addcriteria.addregion == ""){
$('#errorModal').modal('show');
$('.message').text('You must select a Region.');
$('#errorModal').on('hidden.bs.modal', function(){
document.forms["addEquipForm"].addcriteria.addregion.focus();
});
return false;
}
// several more checks
else{
$.post('api/updateEquip.php', {addcriteria:addcriteria}, function(data){
if(data == "Success"){
$('#successModal').modal('show');
$('.message').text('New Equipment has been added.');
$('#successModal').on('hidden.bs.modal', function(){
location.reload();
});
}
else{
$('#errorModal').modal('show');
$('.message').text('The Equipment could not be added.');
return false;
}
});
}
});
As stated, I have many onClick events that look similar to the above. I want to get better at creating custom functions, and I think this would be a good start.
This was my attempt at creating a custom reusable function for the above code...
I started by creating the function:
function criteriaCheck(checkCriteria){
if(checkCriteria == ""){
$('#errorModal').modal('show');
$('.message').text('Error message of some sort.');
$('#errorModal').on('hidden.bs.modal', function(){
document.forms["addEquipForm"].checkCriteria.focus();
});
return false;
}
else{
// not sure what to return here
// but I can console log a success message
console.log('Success');
}
}
Then, inside my onClick
event, I can call the function and pass the value into the function:
var checkCriteria = '';
criteriaCheck(checkCriteria = addcriteria.addcity);
However, using these updates, I can only get "Success" in the console, even when I try to leave a blank form value.
With all of this said, how can I build a custom reusable function using the above onClick
event?
checkCriteria=addcriteria.addcity
), so your function is only receiving TRUE. Just pass the object itself. \$\endgroup\$