HTML Form with Submit Button, No Refresh

Viewed 67

I have a form:

<form id="inviteForm" action="">
            <div class="modal-body">
                <label>Name</label>
                <input type="text" class="form-control mb-3" id="inputName" placeholder="Name" name="name" required>
                <label>Email</label>
                <input type="email" class="form-control" id="inputEmail" placeholder="Email" name="email" required>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-success" onclick="invite()">Invite</button>
            </div>
        </form>

You can see that I have a submit button. I like that the submit button checks the form validity, but don't want to submit anything when it is pressed (this is all handled by the invite() js method).

How can I continue to use the submit button as a form validator but not submit anything with it?

1 Answers

Instead of using:

onclick="invite();"

Consider using:

onclick="return invite();"

or using:

onclick="invite(); return false;" // This will cease the form submission at any cost.

However, the first option will return the value of the return value of invite() function to the event listener. You can decide whether you wanna submit or not, using a simple check something like this:

function go() {
  return document.getElementById("chk").checked;
}
<form action="https://www.example.com/">
  <input type="checkbox" id="chk" />
  <input type="submit" value="Check to Go" onclick="return go();" />
</form>

Related