Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!