Home > Enterprise >  how to avoid page refresh when user types in invalid form input
how to avoid page refresh when user types in invalid form input

Time:07-27

I have a simple "contact me" section on my website and I'm trying to figure out how to prevent the page on refreshing when a user enters in an invalid email. Reason why I want to prevent this is because when they enter in an invalid email the page refreshes and brings them to the top of the page. I have an error that displays what the user missed but they have to scroll back down to the contact section to see it. I'm not sure how to go about preventing the page from scrolling to the top after they submit. All I have right now is a simple php form validation. Any suggestions? would this be done with JavaScript? or can I add this to my existing php validation script? not sure where to start. thanks!

CodePudding user response:

It depends on what you mean by an invalid email. If you are referring to the format then something like this is what you should be using, and the browser will check the email for you.

        <label for='idEmail' >Your email address</label>
        <input type='email' name='inpEmail' id='idEmail' class='full_width'
         maxlength='100' autocomplete='email' value=''>

The critical bit is making the input as type email

CodePudding user response:

The commenter above means

e.preventDefault().

 const handleSubmit = (e) => {
    e.preventDefault();
    alert("you just clicked the button").
 }

<form onSubmit={handleSubmit}>
     <button type="submit" onClick={onSubmit}>Click Me</button>
</form>

Including that e.preventDefault() keeps the page from reloading.

  • Related