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

158
Visualizações
html js not valid error message still appearing when input is correct

I have the following input field with js validation to input a name and when the field is left blank an error message appears which is what I required however when I enter a name it accepts the input in my form however the same error message pops up stil briefly.

function myFunction() {

  let x = document.getElementsByName("first_name")[0].value;

  let text;
  text = "";
  if (x == '' || x == null) {
    text = "Input not valid";
  }
  document.getElementById("first_name_errors").innerHTML = text;
}

document.addEventListener('invalid', (function() {
  return function(e) {
    e.preventDefault();
    document.getElementsByName("first_name").focus();
  };
})(), true);
<input type="text" name="first_name" placeholder="first name" name class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="myFunction()">

How can i fix this?

Moroever, I intend to use this template for other fields such as email and password fields assuming that the main part of this code I need to focus adapting is?:

let text;
  if (x == '' ||  x == null) {
    text = "Input not valid";
  }

Help/advice is much appreciated. Thanks

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You have to take the first element of the NodeList returned by getElementsByName("first_name")

Like this:

let x = document.getElementsByName("first_name")[0].value;
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