0

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();        
    }
    
});
5
  • 1
    Well have you checked what emptyFields contains, with console.log(emptyFields)? Commented Dec 3, 2020 at 13:49
  • if (!emptyFields.length) { $.post(/* ... */) } so, this executes only if emptyFields.length is 0. Is that correct? Commented Dec 3, 2020 at 13:50
  • console.log(emptyFields) is empty. [] What's going on? Commented Dec 3, 2020 at 13:51
  • 1
    You check for "" and null but not undefined. Commented Dec 3, 2020 at 13:52
  • If the array is empty then the if condition is working correctly (no surprise there.) The problem is then earlier in the code. You need to do more basic debugging, e.g. console.log(fields) to confirm that it contains what you expect, and so on. Commented Dec 3, 2020 at 13:53

1 Answer 1

3

From the jQuery Documentation of .val() (emphasis added)

The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

You do not check for undefined, you check for empty string or null.

if (fields[key] === "" || fields[key] === undefined) {
  emptyFields.push(key);
}

Here is a stripped down version with the undefined fix, a value with "" and a value with undefined

let umbrellaCount = "1"
let siteStatus = ""
let servicesRendered = "1"
let afterServiceStatus = undefined

const fields = {
  "Umbrella Count": umbrellaCount,
  "Site Status": siteStatus,
  "Services Rendered": servicesRendered,
  "After Service Status": afterServiceStatus
}

console.log(JSON.stringify(fields, null, 2))

var emptyFields = [];
Object.keys(fields).forEach((key) => {
  if (fields[key] === "" || fields[key] === undefined) {
    emptyFields.push(key);
  }
});

console.log(emptyFields)

if (!emptyFields.length) {
  console.log(true);
} else {
  console.log(false);
}

Sign up to request clarification or add additional context in comments.

5 Comments

Copied and paste your codes to my codes, the emptyFields array is still empty.
Do any of the fields match "", null, or undefined? This is definitely a problem in your code, and there may be something else going on that we cannot know without more information.
Have you tried something like console.log(JSON.stringify(fields, null, 2))? That would help spot something like a " " value
@TengBangWei I've added code with some values that do trigger the "false" path of the if/else, and it does work correctly.
Thank you @crashmstr, it worked now. Not sure what happened though. It's late in Asia now. So I will study the codes tomorrow morning and update this thread subsequently.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.