Clearing input fields is a vital yet underrated aspect of form UX. When building robust web forms, developers need to provide users with a way to easily clear fields or even reset the entire form.
Without this ability, users get frustrated and abandon forms without completing them. According to Baymard Institute, the average form abandonment rate across industries is 78%.
In this comprehensive technical guide, we’ll dig into the reasons users abandon forms. We’ll explore the various imperative techniques available in JavaScript to clear input fields programmatically.
Why Users Abandon Forms
To better understand the use cases for clearing fields, let’s first analyze why users leave forms incomplete:
1. Changed their mind – Form filling is a commitment vulnerable to user whims. People often start completing forms casually to explore products or content. Midway when the time investment feels too high, they drop off. Clearing fields allows picking up where they left.
2. Error recovering fields – Validation errors after submitting a form causes loss of entered data. Users need to re-enter everything. Clear reset option avoids the rework making forms less intimidating.
3. Fixing accidental submission – 22% users have submitted a form by mistake. Instant clear buttons minimize wasted effort re-filling forms due to mis-clicks.
4. Changing form context – Dynamic filters, conditional logic & multi-page forms require changing field values based on selections. Clearing dependent fields allows context reset.
Understanding user psychology behind abandonments uncovers situations where giving users the power to rollback form state reduces abandonments.
Next we‘ll seeclever techniques that enable easy field clearing in JavaScript.
Methods to Clear Input Fields
Below are the most common ways to reset form fields in JavaScript:
1. Set Value to Empty String
Setting the input‘s value
property to empty string ‘‘
clears contents:
const nameInput = document.getElementById(‘name‘);
nameInput.value = ‘‘;
For multiple inputs:
const inputs = document.querySelectorAll(‘input‘);
inputs.forEach(input => {
input.value = ‘‘;
});
This simplicity comes at the cost of tediously selecting each input individually.
2. Use reset() Method
Forms have an inbuilt reset()
method to restore initial values:
const form = document.getElementById(‘form‘);
form.reset();
reset()
clears all inputs within that <form>
tag collectively. Resetting the entire form gives a fresh slate without leaving remnants behind.
As per whatwg standards, calling reset()
also resets other form attributes like disabled
to initial state.
3. Set Value to Default
An input element‘s defaultValue
contains the default preset value. We can restore defaults using:
comments.value = comments.defaultValue;
This even works for textareas and select dropdowns, unlike empty string approach.
However, retaining predefined values can be counterintuitive for uses expecting a blank state.
4. Use onfocus Event
The onfocus
event fires when an input gets focus:
function clearInput(e) {
e.target.value = "";
}
input.addEventListener(‘focus‘, clearInput);
But this may clear fields unexpectedly while tabbing which can confuse users.
5. Use onclick Event
Alternatively, attach clear logic to a reset button‘s click handler:
function clearFields() {
// clear logic
}
clearBtn.onclick = clearFields;
Giving control to the user reduces accidental data loss. But we need extra elements like buttons and click handlers.
Now that we‘ve seen key approaches for clearing fields, next we‘ll explore nuances for different input types.
Clearing Various Input Types
Resetting values requires specialized handling for certain input types like files or checkboxes:
Clear Text Inputs
Text fields have a simple value
property that can be emptied:
const name = document.getElementById(‘name‘);
name.value = ‘‘;
The same applies for inputs like email, URL, search, number etc. But for passwords, use defaultValue
to show dots.
Clear Textareas
Textareas also expose the value
property:
comments.value = ‘‘;
While most ways of clearing inputs also apply to textareas, type
specific methods like checked won‘t.
Clear Checkboxes and Radio Buttons
Checkboxes and radios have a checked
property instead of value. Unchecking them clears selected state:
const checkedInputs = document.querySelectorAll(‘input[type="checkbox"]:checked‘);
checkedInputs.forEach(input => {
input.checked = false;
});
We specifically target checked ones instead of all to retain any default selections.
Clear File Input
Due to security restrictions, the browser doesn‘t allow JavaScript to directly access file contents from <input type="file">
.
So to reset picked files, we replace it with a fresh input element:
function clearFileInput() {
const newInput = document.createElement(‘input‘);
newInput.type = fileInput.type;
// replace with new input
fileInput.parentElement.replaceChild(newInput, fileInput);
}
Constructing a new input from scratch gives us a blank file picker.
Clear Select/Dropdown
Dropdowns have a selectedIndex
property to track selected option by index.
categorySelect.selectedIndex = -1; //deselect
Setting it to -1 ensures no option stays selected after clearing dynamic selects.
Clear Range Input
For sliders, resetting to a logical default value clears selected range:
ageInput.value = 25; // default
Summary of Clearing Approaches
This table summarizes appropriate clearing approaches for each input type:
Input Type | Preferred Method |
---|---|
Textbox | Set value to ‘‘ |
Text Area | Set value to ‘‘ |
Checkboxes/Radios | Set checked to false |
Select/Dropdown | Set selectedIndex -1 |
File Input | Replace with new element |
Range Slider | Set value to default |
Next let‘s assess the trade-offs between clearing specific fields vs full form reset.
Clearing Forms vs Individual Inputs
We‘ve covered both clearing individual <input>
elements and calling form-level reset()
to reset all inputs in one go.
But should we clear fields separately or always reset the full form?
Clearing all fields via reset()
ensures the form is in a harmonious blank state instead of mix of cleared and uncleared values.
However for partially editable forms, calling form-level reset erases readonly contextual data that users still need to refer.
Resetting dynamic filters and sort orders can also make forms confusing by altering their context drastically.
So while resetting entire forms works great for short linear forms, clearing specific fields shines for:
- Multi-page forms – Maintain context across pages by only clearing page-level fields
- Partial resets – Retain certain static selections like categories while resetting other conditional fields
- Dynamic forms – Surgically reset only dynamic sections as needed
In summary, opt for targeted field clearing when you need to selectively rollback parts of a large form. Use form reset() for typical small-scale cases.
With this context on high-level trade-offs, let‘s tackle some common real-world use cases next.
Clearing Fields on Form Submit
A typical requirement is clearing form fields after submission to prepare for next inputs.
Here the submit
event comes handy to reset after http requests finish:
form.addEventListener(‘submit‘, () => {
form.reset();
});
This ensures the form starts fresh once the current submission concludes.
For dynamic content powered by client-side frameworks, reset won‘t apply to new fields missing initially.
In such cases, we need to manually clear dynamic portions:
const additionalFields = document.getElementById(‘dynamicSection‘);
form.addEventListener(‘submit‘, () => {
additionalFields.querySelectorAll(‘input‘).forEach(input => input.value = ‘‘);
form.reset();
});
First reset dynamic inputs, then reset initial static fields.
Resetting File Input Before Upload
Another great UX enhancement is clearing file picker after selecting files right before upload.
This prepares it for further uploads making the experience less disruptive:
const imgInput = document.getElementById(‘image-upload‘);
imgInput.addEventListener(‘change‘, () => {
uploadImage();
// reset
imgInput = getFreshFileInput();
});
function getFreshFileInput() {
//file input replace logic
}
Here the picker resets to blank state after completing one upload, ready for next selection.
We reusable encapsulate the reset logic in a separate function to keep main flow clean.
Clearing Fields After Timeout
For idle timeout based field clearing, the setTimeout()
API sets a timer to reset after interval elapses:
let idleTimer;
inputs.forEach(input => {
input.addEventListener(‘input‘, () => {
clearTimeout(idleTimer);
idleTimer = setTimeout(() => {
form.reset();
}, 60 * 1000);
});
});
Any input activity clears existing timer. Without activity for 60 seconds, form resets.
The configurable timeout allows granular control over idle duration thresholds before clearing.
Persisting Cleared Field State after Validation
When users fill details and submit, validation errors can erase cleared fields requiring re-entry:
1. User fills form
2. Clicks submit
3. Validation fails - cleared fields reset
4. User re-enters data in erased fields
This hampers UX. We can maintain cleared fields by only resetting after successful submission:
form.addEventListener(‘submit‘, event => {
if(formHasErrors(form)) {
// don‘t reset on error
} else {
form.reset();
}
});
Here fields clear only on clean submits without validation errors. Else earlier effort stays intact.
Accessibility Concerns for Dynamic Fields
When constructing accessible forms with ARIA tags, dynamic content requires announcing updates to screen readers:
function resetAdditionalFields() {
// clear inputs
ariaLiveRegion.textContent = ‘Additional fields reset‘;
}
We inform assistive devices of programmatic state changes by injecting messages into a live region wrapper that reads out updates.
This keeps visually impaired users in the loop about off-screen DOM changes triggered via field clearing scripts.
Summary
Let‘s recap the key highlights:
Why clear fields
- Minimize abandonments in long forms
- Recover easily after submission errors
- Fix accidental submissions
- Reset context in dynamic forms
How to clear
- Set input value = ‘‘
- Use form reset() method
- Replace file input reference
When to clear
- On form submit
- Before uploads
- After timeout period
- On field change
Individual vs form reset
- Full reset for short linear forms
- Targeted field clearing for complex multi-page forms
Equipping forms with correct undo behaviors improves the filling experience by allowing easy recovery. Mastering field clearing positions us to build more robust web applications with reduced user friction.