EN
HTML - submit input
6
points
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>