Use the event
object to Get form values on submit in JavaScript. This object will be passed to the submit event listener. To access the form element use event.target
and then get the values of the form fields using the value
property of each field.
Get form values on submitting an example
A simple HTML example code gets the value of submitting the form and shows it in this console log.
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
<script>
const form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
event.preventDefault(); // prevent the default form submission
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
console.log(`Name: ${name}`);
console.log(`Email: ${email}`);
// do something with the form values...
});
</script>
</body>
</html>
Output:
Comment if you have any doubts or suggestions on this Pytho form topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version