How to avoid the user from repeating to fill in the form if there is an error?

Viewed 69

Problem: I'm doing a form to be filled by the user. Once the user clicks submit, if there is an error in the form, it will show an alert. However, when the user clicks "ok" the form will reset all the fields that have been filled so the user needs to repeat in fill in the form all over again.

Question: How to fix this so that when the user clicks "ok" the data is still there?

4 Answers

To stop the page from re-loading add return false; after alert statement, it stops the default action from taking place from the form submit.

alert("Please fill in all mandatory fields");
return false;

You should reset form:

document.getElementById("formId").reset();

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  • Use <button type="button"> to override default submission behavior.
  • Use event.preventDefault() in the onSubmit event to prevent form submission.
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); } 
form.addEventListener('onSubmit', handleForm);

I have something that does exactly that. It's a complete working code, but I am going to give you the task of figuring out which part does what.

function submitInfo(e){
  var fields = document.getElementsByClassName('input-field').length;
  for(let x = 0; x < fields; x++){
    var value = document.getElementById(x).value;
    if(value == ''){
       e.preventDefault();
     var element = document.getElementById(x);
     element.classList.add('no-value');
     setTimeout(function(){
        element.classList.remove('no-value')
     },3000);
     break;
    }
  }
}
.no-value {
  border: 2px solid red;
}
<form method="post" action="">
  <input type="text" name="email" placeholder="Email" class="input-field" id="0"/><br/>
  <input type="password" name="password" placeholder="Password" class="input-field" id="1"/><br/>
  <input type="submit" value="Submit" onclick="submitInfo(event)"/>
</form>

I hope this is what you are looking for.

Related