Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

303
Views
javascript addeventlistener passing the codes to execute for shorter code

Is there a way that I can shorten this code. They have similar condition but different codes to execute. the first one is when I keydown the element will show or hide, the second one after I click the button or submit the form, it will stop or pass the user.

textInput.addEventListener("keydown", function myFunction(){
  if(textInput.value.match(characters)){
    invalidFeedback.style.display = "block";
  }
  else if (textInput.value === ""){
    invalidFeedback.style.display = "block";
  } else {
    invalidFeedback.style.display = "none";
  }
});


form.addEventListener("submit", function (event, myFunction){
  if(textInput.value.match(characters)){
    event.preventDefault();
  }
  else if (textInput.value === ""){
    event.preventDefault();
  }
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

When multiple conditional statements have the same outcome, we can use the || operator, which is like "OR".

We can also export common checks to functions, to keep things granular, neat, and easy-to-consume.

Finally, in the "keydown" event, I introduced a guard clause, which returns the desired outcome on a satisfied condition. It's much easier to read than nested if/else statements.

const doesMatch = () => textInput.value.match(characters);
const isEmpty = () => textInput.value === "";

textInput.addEventListener("keydown", () => {
  if (doesMatch() || isEmpty()) 
    return invalidFeedback.style.display = "block";
  invalidFeedback.style.display = "none"; 
});

form.addEventListener("submit", (event) => {
  if (doesMatch() || isEmpty()) event.preventDefault();
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!