Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a flag function to validate form fields not working

let flags = false
let newTrackerName = document.querySelector(".newTrackerName")
let newTrackerDate = document.querySelector(".newTrackerDate")
let createTracker = document.querySelector(".createTracker")
let trackerTypeOptions = document.querySelectorAll(".trackerTypeOptions")


createTracker.onclick = () => {

  checkFields(flags)


  if (flags === false) {
    console.log(newTrackerName.value, newTrackerDate.value);
  }
}

const checkFields = flags => {
  if (newTrackerName.value === "") {
    prompts(newTrackerName.getAttribute("title"), "cannot be blank.")
    return flags = true
  }
}

const prompts = (title, message) => {
  console.log(`${title} ${message}`)
}
<div class="newTrackerForm mt-10 flex flex-col gap-y-8 font-bold">
  <div class="uppercase text-xs flex flex-col gap-y-2 text-slate-200">
    <span class="tracking-widest">Name:</span>
    <input type="text" name="" id="" class="newTrackerName rounded-lg px-2 py-3 text-xs bg-slate-800 uppercase" title="Tracker Name" />
  </div>
  <div class="uppercase text-xs flex flex-col gap-y-2 text-slate-200">
    <span class="tracking-widest">Start Date:</span>
    <input type="date" name="" id="" class="newTrackerDate rounded-lg px-2 py-3 text-xs bg-slate-800" title="Tracker Start Date" />
  </div>
  <div class="uppercase text-xs flex flex-col gap-y-2 text-slate-200">
    <span class="tracking-widest">Type:</span>
    <div class="flex items-center gap-x-2 tracking-widest">
      <input type="radio" name="trackerTypes" id="" class="trackerTypeOptions" value="yesNo" /> Yes/No
      <input type="radio" name="trackerTypes" id="" class="trackerTypeOptions" value="counts" /> Counts
    </div>
  </div>

</div>
<button class="createTracker bg-emerald-600 p-3 rounded-lg text-slate-300 font-bold uppercase tracking-widest">Create</button>

</div>

I have a form which is validating user’s inputs.

I created a function that checks for empty fields and other checks. I have created a flag variable which returns true if a field is empty and the form will store the data.

However, when I click on the create button , the error prompt is shown with the correct message BUT it also shows the data from other fields. Ideally, it should only show data from all the fields if the flag variable returns false.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let flags = false

createTracker.onclick = () => {

    checkFields(flags) 

    if (flags === false) {
        console.log(document.querySelector("input[name='trackerTypes']:checked").value, newTrackerName.value, newTrackerDate.value, 
minCountRange.value, maxCountRange.value, tagValue);
    }
}

const checkFields = flags =>  {
    if(newTrackerName.value === "") {
        prompts(newTrackerName.getAttribute("title"), "cannot be blank.")
        return flags = true
    }
}

let errors = document.querySelector(".errors")
let closeErrorWindow = document.querySelector(".closeErrorWindow")

let errorMessage = document.querySelector(".errorMessage")
const prompts =  (title, message) => {
    errors.classList.remove("-right-[2000px]")
    errors.classList.add("right-0")
    errorMessage.innerHTML = `${title} ${message}` 
}

I have added all the checks in the checkFields function so I can easily manage if I add new fields or want to add more checks to a particular field.

Any suggestions on what I am doing wrong here?

>Solution :

You are expecting flags to be modified in checkFields() function. However, the function parameter flags creates a local instance of the variable, which then modifies the value of the local instance.

Come to think of it, flags is already a global variable. You don’t have to pass it to any function. You should be able to check its value and modify it in any function (which is dangerous).

So there are two things you can do:

  1. Stop passing the global variable around.
let flags = false;

const checkFields = () =>  {
    if(newTrackerName.value === "") {
        prompts(newTrackerName.getAttribute("title"), "cannot be blank.")
        return flags = true
    }
}

OR

  1. don’t create a global variable
const checkFields = () =>  {
  return newTrackerName.value === ""
}

...

const flag = checkFields();

if (flag) {
  prompt(newTrackerName.getAttribute("title"), "cannot be blank.")
}

if (flag === false) {
  ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading