Skip to content

Instantly share code, notes, and snippets.

@codebubb
Created August 21, 2019 12:54
Show Gist options
  • Select an option

  • Save codebubb/3ad3c1d48594dc13c0261ffd1d41c17b to your computer and use it in GitHub Desktop.

Select an option

Save codebubb/3ad3c1d48594dc13c0261ffd1d41c17b to your computer and use it in GitHub Desktop.
Quick example of how to submit a form with JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Submit a form with JavaScript</title>
<style>
html, body {
height: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
}
form {
display: flex;
flex-direction: column;
}
</style>
</head>
<body>
<form id="registerForm">
<label for="username">Username</label>
<input type="text" name="username" id="username">
<label for="password">Password</label>
<input type="password" name="password" id="password">
<label for="password">Confirm Password</label>
<input type="password" name="confirmPassword" id="confirmPassword">
<button>Register</button>
</form>
<script>
registerForm.addEventListener('submit', (event) => {
event.preventDefault();
const formData = Array.from(registerForm.elements)
.reduce((acc, { id, value }) => ({ [id]: value, ...acc }), {})
delete formData[''];
// Send ajax request e.g.
console.log(formData);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment