HTML5 form events and APIs
HTML5 has introduced many new events and APIs for forms, greatly enhancing their interactivity and functionality. From real-time validation to dynamic content control, these features allow developers to handle user input and data submission more flexibly.
Form Events
HTML5 introduced a series of new events specifically designed to handle interactions with form elements. These events can monitor user input, validation state changes, and other behaviors.
input Event
The input
event is triggered when the value of a form element changes, applicable to <input>
, <textarea>
, and <select>
elements. Unlike the change
event, the input
event triggers every time the value changes, not just when the element loses focus.
document.getElementById('username').addEventListener('input', function(e) {
console.log('Current input value:', e.target.value);
});
invalid Event
The invalid
event is triggered when a form element's value fails validation. It can be used in conjunction with HTML5's built-in validation features.
document.getElementById('email').addEventListener('invalid', function(e) {
e.preventDefault(); // Prevent default error message
this.setCustomValidity('Please enter a valid email address');
});
change Event
The change
event is triggered when a form element's value changes and the element loses focus. For <input type="checkbox">
and <input type="radio">
, it triggers immediately when the checked state changes.
document.getElementById('subscribe').addEventListener('change', function(e) {
console.log('Subscription status:', e.target.checked);
});
Form Validation API
HTML5 provides a complete set of client-side form validation APIs, enabling basic validation without JavaScript while also offering advanced customization options.
checkValidity() Method
Checks whether a form element passes validation and returns a boolean.
const form = document.getElementById('myForm');
if (form.checkValidity()) {
// Form validation passed
} else {
// Form validation failed
}
setCustomValidity() Method
Sets a custom validation message to display when validation fails.
const password = document.getElementById('password');
password.addEventListener('input', function() {
if (this.value.length < 8) {
this.setCustomValidity('Password must be at least 8 characters');
} else {
this.setCustomValidity('');
}
});
validity Property
Returns a ValidityState
object containing detailed validation status information.
const email = document.getElementById('email');
console.log(email.validity);
/*
{
valueMissing: false,
typeMismatch: true,
patternMismatch: false,
tooLong: false,
tooShort: false,
rangeUnderflow: false,
rangeOverflow: false,
stepMismatch: false,
badInput: false,
customError: false,
valid: false
}
*/
New Form Elements and Attributes
HTML5 added several new form elements and attributes to enhance functionality.
datalist Element
Provides a list of input suggestions, allowing users to select or enter their own value.
<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
<option value="Edge">
<option value="Opera">
</datalist>
output Element
Displays calculation results or script output.
<form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
<input type="range" id="a" value="50"> +
<input type="number" id="b" value="25"> =
<output name="result" for="a b">75</output>
</form>
Form Data API
FormData Object
Easily collects and manages form data, especially useful for AJAX submissions.
const form = document.getElementById('myForm');
const formData = new FormData(form);
// Add extra data
formData.append('timestamp', Date.now());
// Send data
fetch('/submit', {
method: 'POST',
body: formData
});
entries() Method
Iterates over key-value pairs in a FormData
object.
for (let [key, value] of formData.entries()) {
console.log(key, value);
}
File Upload API
HTML5 enhanced file upload functionality with more precise control.
multiple Attribute
Allows selecting multiple files.
<input type="file" id="fileUpload" multiple>
File API
Accesses file information and previews content.
document.getElementById('fileUpload').addEventListener('change', function(e) {
const files = e.target.files;
for (let i = 0; i < files.length; i++) {
console.log(`Filename: ${files[i].name}, Size: ${files[i].size} bytes`);
// Image preview
if (files[i].type.match('image.*')) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.createElement('img');
img.src = e.target.result;
document.body.appendChild(img);
};
reader.readAsDataURL(files[i]);
}
}
});
Date and Time Inputs
HTML5 introduced specialized date and time input types with native browser controls.
<input type="date" id="birthday">
<input type="time" id="alarm">
<input type="datetime-local" id="meeting">
<input type="month" id="month">
<input type="week" id="week">
document.getElementById('birthday').addEventListener('change', function(e) {
console.log('Selected date:', e.target.valueAsDate);
});
Color Picker
The color
input type provides a native color picker.
<input type="color" id="bgColor" value="#ff0000">
document.getElementById('bgColor').addEventListener('input', function(e) {
document.body.style.backgroundColor = e.target.value;
});
Progress Bars and Meters
progress Element
Displays task completion progress.
<progress id="fileProgress" value="0" max="100"></progress>
// Simulate file upload progress
let progress = 0;
const interval = setInterval(() => {
progress += 5;
document.getElementById('fileProgress').value = progress;
if (progress >= 100) clearInterval(interval);
}, 500);
meter Element
Displays scalar measurements or fractional values.
<meter id="diskUsage" value="6" min="0" max="10">6 out of 10</meter>
Form Constraint Validation
HTML5 provides multiple ways to constrain user input.
pattern Attribute
Uses regular expressions to validate input.
<input type="text" id="zipCode" pattern="\d{5}" title="Five-digit ZIP code">
required Attribute
Marks a field as mandatory.
<input type="text" id="username" required>
min, max, and step Attributes
Limits the range and step size of numerical inputs.
<input type="number" id="quantity" min="1" max="10" step="1">
<input type="range" id="volume" min="0" max="100" step="5">
Form Autocomplete
HTML5 improved form autocomplete functionality.
autocomplete Attribute
Controls form autofill behavior.
<form autocomplete="on">
<input type="text" name="name" autocomplete="name">
<input type="email" name="email" autocomplete="email">
<input type="password" name="password" autocomplete="new-password">
</form>
Forms and Web Storage
Combines with the Web Storage API to save form data.
// Save form data
document.getElementById('myForm').addEventListener('input', function() {
const formData = new FormData(this);
localStorage.setItem('formAutoSave', JSON.stringify(Object.fromEntries(formData)));
});
// Restore form data
window.addEventListener('load', function() {
const savedData = localStorage.getItem('formAutoSave');
if (savedData) {
const data = JSON.parse(savedData);
for (const [name, value] of Object.entries(data)) {
const element = document.querySelector(`[name="${name}"]`);
if (element) element.value = value;
}
}
});
Forms and Web Workers
Uses Web Workers to process form data without blocking the UI thread.
// Main thread
const worker = new Worker('form-worker.js');
document.getElementById('processData').addEventListener('click', function() {
const formData = new FormData(document.getElementById('dataForm'));
worker.postMessage(Object.fromEntries(formData));
});
worker.onmessage = function(e) {
document.getElementById('result').textContent = e.data;
};
// form-worker.js
self.onmessage = function(e) {
// Simulate time-consuming processing
const result = doComplexCalculation(e.data);
self.postMessage(result);
};
function doComplexCalculation(data) {
// Complex calculation logic
return 'Processed result';
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:HTML5的表单数据提交方式