Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

307
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda