28

Can I prevent HTML Text Field input even when my field is NOT Disabled or Read-only? I have this requirement.

Maybe I can block all inputs via JS or jQuery?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
gene b.
  • 10,512
  • 21
  • 115
  • 227

5 Answers5

54

See this fiddle

You can use jQuery for this.. You can do it as below

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

OR

you can just return false instead of using preventDefault(). See the script below

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

See the fiddle

OR

A much simplified version without Javascript would be as below. Just change your HTML as below

<input type="text" onkeypress="return false;"/>

See the fiddle

Juan
  • 4,910
  • 3
  • 37
  • 46
Lal
  • 14,726
  • 4
  • 45
  • 70
7

If you're looking for read-only input, a simple way is to add 'readonly' to the input HTML. For example,

<input type="number" readonly>

With this, it doesn't interfere with form submission or other event listeners. Input with 'readonly' will still be submitted, but not input with 'disabled'.

For references: https://www.w3schools.com/TAGS/att_input_readonly.asp

Kyle-Law
  • 212
  • 3
  • 3
5

If you wish to make the field complete in-intractable.

$('input').focus(function(e) {
    $(this).blur();
});

Example : https://jsfiddle.net/DinoMyte/up4j39qr/15/

DinoMyte
  • 8,737
  • 1
  • 19
  • 26
0

You could return false on input event or use .val('') to reset the field when everytime user try to write something :

$('input').input(function(e) {
    $(this).val('');
});

Hope this helps.


$('input').on('input', function(e) {
    $(this).val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

The accepted answer works just fine for me, but I also wanted to include Shift, Esc, and delete keys. In this case use keydown instead of keypress:

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

Documentation: https://api.jquery.com/keydown/

Aljoša
  • 65
  • 5