Input/Output in JavaScript: HTML5 Input, Validation, and the Document Object Model (DOM)
HTML5 Input Elements
HTML5 introduces various input types that help developers create user-friendly forms. Some common types include:
- Text (
<input type="text">
): Captures general text input. - Number (
<input type="number">
): Accepts numeric values. - Email (
<input type="email">
): Requires a valid email format. - Date (
<input type="date">
): Provides a date picker. - File (
<input type="file">
): Allows file uploads. - Checkbox & Radio Buttons (
<input type="checkbox">
,<input type="radio">
): Used for multiple or single selections.
Example: Basic Form with HTML5 Inputs
<form id="userForm">
<label for="name">Name:</label>
<input type="text" id="name" required>
<label for="email">Email:</label>
<input type="email" id="email" required>
<label for="age">Age:</label>
<input type="number" id="age" min="1" max="100" required>
<button type="submit">Submit</button>
</form>
Input Validation in JavaScript
Although HTML5 provides built-in validation, JavaScript allows us to implement custom validation logic for more flexibility.
Example: Validating User Input
document.getElementById("userForm").addEventListener("submit", function(event) {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let age = document.getElementById("age").value;
if (name.length < 3) {
alert("Name must be at least 3 characters long.");
event.preventDefault();
}
if (!email.includes("@")) {
alert("Please enter a valid email address.");
event.preventDefault();
}
if (age < 1 || age > 100) {
alert("Age must be between 1 and 100.");
event.preventDefault();
}
});
The Document Object Model (DOM) and Output Handling
The DOM represents the structure of an HTML document, allowing JavaScript to dynamically update content.
Example: Displaying Output Dynamically
<p id="output"></p>
<button onclick="displayMessage()">Click Me</button>
<script>
function displayMessage() {
document.getElementById("output").textContent = "Hello, welcome to JavaScript!";
}
</script>
This example updates the <p>
tag dynamically when the button is clicked.
Example: Handling User Input Dynamically
<input type="text" id="userInput" placeholder="Type something...">
<p id="display"></p>
<script>
document.getElementById("userInput").addEventListener("input", function() {
document.getElementById("display").textContent = this.value;
});
</script>
In this case, whatever the user types is immediately displayed in the paragraph element, demonstrating real-time interaction.