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

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

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 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