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?

5 Answers 5

55

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Title literally says NOT Disabled/Read-Only. No idea why this is upvoted
Programmatically doing this and setting the disabled attribute on the submit button gets the behaviour asked for
5

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

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

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

Comments

1

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/

Comments

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' />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.