This page looks best with JavaScript enabled

Use onclick event instead of 'submit' in Javascript

 ·   ·  ☕ 2 min read

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.

1
2
3
4
5
<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.

1
2
3
4
5
<!-- ... -->

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

<!-- ... -->

Consider the below example -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things