JavaScript: Prevent Form Submission and Log Inputs
JavaScript Event Handling: Exercise-12 with Solution
Prevent Default Behavior
Write a JavaScript program that prevents the default behavior of a form submission and logs the input values to the console.
Solution 1: Using addEventListener
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form>
<input type="text" name="username" placeholder="Enter your username" required />
<input type="email" name="email" placeholder="Enter your email" required />
<button type="submit">Submit</button>
</form>
</body>
</html>
JavaScript Code:
// Select the form element
const form = document.querySelector('form');
// Add an event listener for the 'submit' event
form.addEventListener('submit', (event) => {
event.preventDefault(); // Prevent the default form submission behavior
// Get input values and log them
const formData = new FormData(form); // Create a FormData object
for (let [key, value] of formData.entries()) {
console.log(`${key}: ${value}`); // Log key-value pairs
}
});
Output:
Enter your username Enter your email Submit
Explanation:
- The querySelector method selects the <form> element in the DOM.
- 2. Add Event Listener:
- A submit event listener is added to the form using addEventListener.
- 3. Prevent Default:
- event.preventDefault() stops the browser from performing the default form submission behavior.
- 4. Extract Form Data:
- FormData is used to retrieve all form input values as key-value pairs.
- 5. Log Form Data:
- The values are logged to the console using a for...of loop.
1. Select the Form:
Solution 2: Inline onsubmit Attribute
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form onsubmit="handleSubmit(event)">
<input type="text" name="username" placeholder="Enter your username" required />
<input type="email" name="email" placeholder="Enter your email" required />
<button type="submit">Submit</button>
</form>
</body>
</html>
JavaScript Code:
function handleSubmit(event) {
event.preventDefault(); // Prevent default behavior
// Get the form reference from the event
const form = event.target;
// Extract and log the input values
const inputs = form.querySelectorAll('input'); // Select all input elements
inputs.forEach((input) => {
console.log(`${input.name}: ${input.value}`); // Log the name and value of each input
});
}
Output:
Enter your username Enter your email Submit
Explanation:
- The onsubmit attribute in the <form> element binds the form submission to the handleSubmit function.
- event.preventDefault() prevents the form from being submitted traditionally.
- event.target provides the form element, and querySelectorAll selects all <input> elements.
- A forEach loop iterates over the inputs, logging their name and value properties.
1. Inline Event Binding:
2. Prevent Default:
3. Access Form Inputs:
4. Log Input Values:
Live Demo:
See the Pen javascript-event-handling-exercise-12 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Event Handling Exercises Previous: JavaScript Event Delegation for Dynamic List items.
Event Handling Exercises Next: Event Bubbling and stopPropagation in JavaScript.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics