Explain Codes LogoExplain Codes Logo

How to prevent user from typing in text field without disabling the field?

html
input-control
form-interoperability
accessibility
Anton ShumikhinbyAnton Shumikhin·Nov 8, 2024
TLDR

Prevent typing in an HTML text field by intercepting and disregarding typed input — a trick utilising JavaScript's addEventListener and preventDefault:

document.querySelector('input[type="text"]').addEventListener('keydown', e => e.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:

<input type="text" name="inputName" readonly>

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:

$('input[type="text"]').on('keydown', function(e) { e.preventDefault(); // Q: Why didn't the input let the letter in? // A: It said, "Sorry, no room. I'm already full of... nothing really." });

This immediately blocks typing efforts, giving users quick feedback loops.

Enforcing text length with HTML

Limit text entry using the maxlength HTML attribute:

<input type="text" name="inputName" maxlength="0">

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:

input[readonly] { user-select: none; /* The equivalent of "No touchy!" in code */ }

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:

<input type="text" onpaste="return false;">

Pasting 'ignored' to ensure comprehensiveness.

Form interoperability

Benefit from fields marked readonly, they still submit their value along with the form, unlike disabled fields.