Use onclick event instead of 'submit' in Javascript

Use onclick rather than submit in HTML forms.

A typical HTML form has a few fields and a button to submit the data to some back-end server. And, the typical way to do the form submission is through the submit method.

<form action="/helloMessage.php">
  <input type="text" id="name" /><br />

  <button type="submit"></button>

On clicking the button, the page will submit data to helloMessage.php, receives any response from PHP page, and (can be configured to) displays the response. [Or, the page could redirect somewhere else based on the submission status, but we will not discuss that here]

Each form submission therefore is followed by a page refresh, which is not a good user experience.

We can avoid the refresh by using a custom function to supply data to server and show response. We will use an event raised on button click to eliminate submit altogether.

<!-- ... -->

<button type="button" onclick="submitSomething()">Submit</button>

<!-- ... -->

Consider the below example -

<!DOCTYPE html>
    <form style="padding-top: 3em;padding-left: 5em">
      <label for="name">Name: </label>
      <input type="text" id="name" /><br /><br /><br />
      <button type="button" onclick="sayHello()">Submit</button>
    <p style="padding-top: 2em; padding-left: 5em" id="helloMsg">
      Enter name and hit button to say 'hello'.
      function sayHello() {
        // send `submit` request to server
        document.getElementById("helloMsg").innerHTML = `Hello, ${
        document.getElementById("name").value = "";

A ‘hello’ message gets displayed on button click without a page refresh.

comments powered by Disqus