How to prevent user from typing in text field without disabling the field?
Prevent typing in an HTML text field by intercepting and disregarding typed input — a trick utilising JavaScript's addEventListener
and preventDefault
:
The keydown
event occurs when a user presses a key down. With the above line of code, we are telling browsers to prevent default behavior of keydown which, in this case, is inputting text into the field.
Available arsenal for input control
Employ the readonly HTML attribute
For maintaining field interactivity, leverage the readonly
attribute on your HTML input element:
Browsers typically refrain from greying out readonly inputs, unlike disabled ones, helping maintain visual aesthetics.
Wresting control with JavaScript
Extend your input control suite with jQuery facilitating an easy application of input rejection:
This immediately blocks typing efforts, giving users quick feedback loops.
Enforcing text length with HTML
Limit text entry using the maxlength
HTML attribute:
A lesser-known trick that maintains field's activity, but keeps additional text entry at bay.
CSS powered text selection prevention
Spruce up readonly
fields by disabling text selection using CSS:
Handling screen-readers
Both readonly and input denial mechanisms keep your field accessible for screen readers, thus ensuring aidgets.
Restricting paste operations
Arrest pasted data entry in a similar vein to typed inputs:
Pasting 'ignored' to ensure comprehensiveness.
Form interoperability
Benefit from fields marked readonly
, they still submit their value along with the form, unlike disabled fields.
Was this article helpful?