Languages
[Edit]
EN

HTML - submit input

6 points
Created by:
nickkk0
647

In this article, we would like to show you how to create submit input element that appears as button in HTML.

Quick solution:

// ONLINE-RUNNER:browser;

<input type="submit" text="Send" />

 

Practical examples

1. Pure HTML form sending

In this example, we create a simple submit button that sends form using POST method to the /path/to/backend. That approach redirects page to /path/to/backend.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <form action="/path/to/backend" method="post">
    <label>
      <span>Username:</span>
      <input type="text" name="username" />
    </label>
    <input type="submit" value="Send" />
  </form>
</body>
</html>

2. Form submit event handling with JavaScript - example 1

In this example, we handle submit action in JavaScript code. return false in onsubmit prevents web page reloading. Programmer should send data in own way in handleSubmit function, e.g. AJAX / fetch() function.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <script>
    
    function handleSubmit(form) {
      	if (form.username.value) {
    		console.log('Username: ' + form.username.value);
        } else {
        	console.warn('Username not set.');
        }
    }
    
  </script>
  <form onsubmit="handleSubmit(this); return false">
    <label>
      <span>Username:</span>
      <input type="text" name="username" />
    </label>
    <input type="submit" value="Send" />
  </form>
</body>
</html>

3. Form submit event handling with JavaScript - example 2

In this example, we handle submit action in JavaScript code. event.preventDefault() in handleSubmit prevents web page reloading. Programmer should send data in own way in handleSubmit function, e.g. AJAX / fetch() function.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <script>
    
    function handleSubmit(event, form) {
      	event.preventDefault();
      	if (form.username.value) {
    		console.log('Username: ' + form.username.value);
        } else {
        	console.warn('Username not set.');
        }
    }
    
  </script>
  <form onsubmit="handleSubmit(event, this)">
    <label>
      <span>Username:</span>
      <input type="text" name="username" />
    </label>
    <input type="submit" value="Send" />
  </form>
</body>
</html>

References

  1. <input type="submit"> - HTML | MDN

Alternative titles

  1. HTML - input type submit
  2. HTML - submit button
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join