0

I'm trying to block all input on an html text field with jQuery. The following solution works on desktop browsers:

that.input.keydown(function (e) {
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();
    return false;
});

However, while it blocks regular input it fails to block backspace on Android (Chrome). I've also tried blocking the keyup and keypress events, but that didn't help. I don't want to set the readonly attribute, because I intend to allow the input in certain situations.

Is there any clean solution for this? Thanks in advance!

  • 2
    *"I don't want to set the readonly attribute, because I intend to allow the input in certain situations."* Why don't you change the `readonly` value on those *"certain situations"*? – Karl-André Gagnon May 07 '18 at 13:43
  • I can't, because this will be determined as you type. If I set the readonly attribute the cursor will disappear and so will the virtual keyboard on the phone. – Andy Kowalski May 07 '18 at 13:53

2 Answers2

2

The reality is that android keyboards are not keyboards. When a text field is opened in android the text-field-owner application and the keyboard application, speaking simply, come to share a resource which is the text field contents. The keyboard app receives the entire contents of the text field and then edits - including deletions - are made locally and pushed to the app via calls like DeleteSurroundingText (for simple deletions of non-text content i.e. whitespace) or setComposingRegion/setComposingText for changes to words. This means that autocorrect can work on already-existing words.

Some android keyboards generate keypress events which reach Chrome, some do not. Sometimes it makes no sense to generate keypress events - if a word is autocorrected what keypresses should be sent?

As you are looking for the keyboard and cursor to be displayed but the field to remain uneditable until later I would suggest you implement some sort of onChange/Revert loop.

Detect all changes to a <input type="text"> (immediately) using JQuery

0

Apparently android keyboards have a strange bug with the keyboard so instead of attaching to the keydown event maybe try the oninput event.

I found more info on this issue here Capture keys typed on android virtual keyboard using javascript

James Harrington
  • 3,138
  • 30
  • 32
  • Unfortunately, this event is not cancellable. I can use it to capture the key press, but I can't block it. Cancellable events (like keydown) can block all input, but they fail with backspace on Android. – Andy Kowalski May 07 '18 at 14:24
  • maybe reset the input to the last value? – James Harrington May 07 '18 at 14:33
  • Looks like it might end up being the only solution. I was hoping there might be something else I'm not seeing. Ah well, thanks for the help anyway! – Andy Kowalski May 07 '18 at 17:05