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>
</form>

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>
<html>
  <body>
    <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>
    </form>
    <p style="padding-top: 2em; padding-left: 5em" id="helloMsg">
      Enter name and hit button to say 'hello'.
    </p>
    <script>
      function sayHello() {
        // send `submit` request to server
        console.log("hello");
        document.getElementById("helloMsg").innerHTML = `Hello, ${
          document.getElementById("name").value
        }!`;
        document.getElementById("name").value = "";
      }
    </script>
  </body>
</html>

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

comments powered by Disqus