Search code examples
javascriptjqueryfunction

Custom function to check blank inputs


Trying to build a custom function that checks for errors and then shows the error.

As of right now, the whole process looks like this:

$("#addRecordSubmit").on("click", function(e) {
  e.preventDefault();
  let errors = "";

  let addobj = {
    addReference: $("#addReference").val(),
    addAccount: $("#addAccount").val(),
    addDescription: $("#addDescription").val(),
    // some more items
  };

  if (addobj.addReference == "") {
    $("#addReferenceError").show();
    errors = errors + 1;
  }
  if (addobj.addAccount == "") {
    $("#addAccountError").show();
    errors = errors + 1;
  }
  if (addobj.addDescription == "") {
    $("#addDescriptionError").show();
    errors = errors + 1;
  }
  // some more if statements

  if (errors > 0) {
    return false;
  } else {
    // process submit
  }
});

So a reusable function would help me out here.

So I started to build a reusable function outside of the on click function above. It currently looks like this:

function checkFormErrors(obj, errorMessage) {
  if(obj == "") {
    $(errorMessage).show();
    errors = errors + 1;
  }
  return errors;
}

Then inside my on click function, I am calling the checkFormErrors function like this:

checkFormErrors(addobj.addReference, "#addReferenceError");

Upon submitting the form, I am getting the console error:

ReferenceError: errors is not defined

What did I do wrong, and how can I make this function work properly?

*** EDIT ***

So I'm passing "errors" from the on click into the checkFormErrors function like so:

$("#addRecordSubmit").on("click", function(e) {
  e.preventDefault();
  let errors = "";

  let addobj = {
    addReference: $("#addReference").val(),
    addAccount: $("#addAccount").val(),
    addDescription: $("#addDescription").val(),
    // some more items
  }

  checkFormErrors(addobj.addReference, "#addReferenceError", errors);

  if (errors > 0) {
    return false;
  } else {
    // process submit
  }
});

So the checkFormErrors function now looks like this:

function checkFormErrors(obj, errorMessage, errors) {
  if(obj == "") {
    $(errorMessage).show();
    errors = errors + 1;
  }
  return errors;
}

I'm no longer getting the "error is not defined" message, but I am not getting the error count returned back into the on click function.

How can I fix this?


Solution

  • There seem to be be a few things going on here:

    1. let creates a block-scoped variable, so it can only be used within the block it's declared it. You would need to create a global variable instead or pass the variable to checkFormErrors().
    2. checkFormErrors() returns the error count, but you're not saving the result to use in your click listener. Update errors with errors = checkFormErrors(...);