I have the following piece of code in my app.js and when the submit button is pressed, it will send a bunch of information collected from a form to my express server. However, it is supposed to do some checking before and if the conditions are not fulfilled, it will not send that information to the server, instead, it will show me a prompt with a list of fields that are required but left empty.
But my app.js sends the information to my express server whether there is an empty field or not and I can't figure out why. There is no error message, the only error message is a post 404 not found which means my app.js sent the information to the server without checking the if/else condition and I'm not sure what I am doing wrong.
if it helps, I am using jQuery instead of DOM manipulation and also uses the jQuery ajax function for posting to my express server. The posting part is fine, the if/else is not.
I found this, this and this. But none of those seems to be able to answer my question.
app.js
$('#submitBtn').on("click", (event) => {
event.preventDefault();
let rackId = $("#umbrella_id").val();
let umbrellaCount = $('#umbrella_count').val();
let siteStatus = $('#site_status').val();
let servicesRendered = $('#services_rendered').val();
let afterServiceStatus = $('#aft_service_status').val();
let remarks = $('#remarksTextarea').val();
if (!remarks) {
remarks = "Nil";
}
const fields = {
"Umbrella Count": umbrellaCount,
"Site Status": siteStatus,
"Services Rendered": servicesRendered,
"After Service Status": afterServiceStatus
}
var emptyFields = [];
Object.keys(fields).forEach((key) => {
console.log(key)
if (fields[key] === "" || fields[key] === null) {
emptyFields.push(key);
}
});
if (!emptyFields.length) {
$.post(`/submit/${rackId}/${umbrellaCount}/${siteStatus}/${servicesRendered}/${afterServiceStatus}/${remarks}`)
loadScreen(false);
} else {
// Show the prompt
for (x in emptyFields) {
// Append the name of fields that are empty to the prompt
$('#populateEmptyFields').append(emptyFields[x]);
}
$('#emptyFieldWarning').removeClass('position-relative').addClass('position-absolute');
$('#emptyFieldWarning').prop('hidden', false);
$('#emptyFieldWarning').show();
$('#warningDialog').prop('hidden', false);
$('#warningDialog').show();
}
});
emptyFieldscontains, withconsole.log(emptyFields)?if (!emptyFields.length) { $.post(/* ... */) }so, this executes only ifemptyFields.lengthis0. Is that correct?[]What's going on?""andnullbut notundefined.console.log(fields)to confirm that it contains what you expect, and so on.