Search code examples
javascripthtmlfunctionreturn

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.


Solution

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