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

Viewed 177053

I tried:

$('input').keyup(function() {

   $(this).attr('val', '');

});

but it removes the entered text slightly after a letter is entered. Is there anyway to prevent the user from entering text completely without resorting to disabling the text field?

12 Answers

If you want to prevent the user from adding anything, but provide them with the ability to erase characters:

<input value="CAN'T ADD TO THIS" maxlength="0" />

Setting the maxlength attribute of an input to "0" makes it so that the user is unable to add content, but still erase content as they wish.


But If you want it to be truly constant and unchangeable:

<input value="THIS IS READONLY" onkeydown="return false" />

Setting the onkeydown attribute to return false makes the input ignore user keypresses on it, thus preventing them from changing or affecting the value.

For a css-only solution, try setting pointer-events: none on the input.

One option is to bind a handler to the input event.

The advantage of this approach is that we don't prevent keyboard behaviors that the user expects (e.g. tab, page up/down, etc.).

Another advantage is that it also handles the case when the input value is changed by pasting text through the context menu.

This approach works best if you only care about keeping the input empty. If you want to maintain a specific value, you'll have to track that somewhere else (in a data attribute?) since it will not be available when the input event is received.

const inputEl = document.querySelector('input');

inputEl.addEventListener('input', (event) => {
  event.target.value = '';
});
<input type="text" />

Tested in Safari 10, Firefox 49, Chrome 54, IE 11.

The best solution is to unfocus input once user clicks it so it makes it kinda readonly

  onFocus={e => e.target.blur()}
Related