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

224
Vistas
Why does my Javascript code runs and disappear immediately

I wrote the codes below to display the user's names when the user enter their name. But the name will appear and disappear immediately. What is wrong?

html codes

<div>
   <p id="names"></p>
</div>

<form method = "get" action = "">
   Enter first name: <input type = "text" id = "firstName"/>
   Enter last name: <input type = "text" id = "lastName"/>
   <input type = "submit" value = "submit" onclick = "return firstName_lastName();"/>
</form>

Javascript code

function firstName_lastName() {
   var firstName = document.getElementById('firstName').value;
   var lastName = document.getElementById('lastName').value;
   var names = document.getElementById('names');

  if (firstName == "" || lastName == "") {
   alert('Please fill in all the fields');
   return false; 
  } else {
    names.innerHTML = firstName + " " + lastName; 
   return true; 
}

The code works but the names appear and disappear immediately.

Edit: The code runs but when the submit button is clicked, the entered first and last names appear on the browser and disappear immediately. The alert also works perfectly when any or both of the fields are not filled.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

submit button is basically submitting form to server and reloading page when clicked but if you want to validate before submit you can use preventDefault to stop page reload see example below

function firstName_lastName(event) {
    event.preventDefault() // to stop submit
    var firstName = document.getElementById('firstName').value;
    var lastName = document.getElementById('lastName').value;
    var names = document.getElementById('names');

    if (firstName == "" || lastName == "") {
        alert('Please fill in all the fields');
    }
    names.innerText = `${firstName} ${lastName}` 
}
<div>
   <p id="names"></p>
</div>

<form method = "get" action = "">
   Enter first name: <input type = "text" id = "firstName"/>
   Enter last name: <input type = "text" id = "lastName"/>
   <input type = "submit" value = "submit" onclick = " firstName_lastName(event);"/>
</form>

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