Besat
Besat

Reputation: 1438

How to have button in the form which check for required fields on submit but does not refresh the page?

I need to have a form with a button which on submit, check for required field but does not refresh the page.

<form>
    <fieldset>
        <input type="text" id="firstname" placeholder="First Name" required/>
        <input type="submit" value="Send"/>
    </fieldset>
</form>

If I disable on submit for form, it wont check for required fields anymore. I need all the functionality of onSubmit but without refreshing the page.

I will appreciate any help.

Upvotes: 0

Views: 45

Answers (1)

Bram
Bram

Reputation: 3283

I'm unsure why you are getting an error. The code provided should work. Try adding an action and a method just in case as follows:

<form action="" method="POST" onsubmit="myFunction()">
    <fieldset>
        <input type="text" id="firstname" placeholder="First Name" required>
        <input type="submit" value="submit">
    </fieldset>
</form>

You can then add a function called myFunction down below as follows:

<script>
    function myFunction() {
        alert("Form was submitted");
    }
</script>

Upvotes: 1

Related Questions