Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda