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

Solution 1:

A non-Javascript alternative that can be easily overlooked: can you use the readonly attribute instead of the disabled attribute? It prevents editing the text in the input, but browsers style the input differently (less likely to "grey it out") e.g. <input readonly type="text" ...>

Solution 2:

if you don't want the field to look "disabled" or smth, just use this:

onkeydown="return false;"

it's basically the same that greengit and Derek said but a little shorter

Solution 3:

$('input').keydown(function(e) {
   e.preventDefault();
   return false;
});

Solution 4:

$('input').keypress(function(e) {
    e.preventDefault();
});

Solution 5:

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.