5

I want to create a text input which does not allowed to input any character (same as disabled input, but the mouse cursor still shown)

function loadPage() { const el = document.getElementById('input-id'); el.addEventListener('keydown', (event) => { event.preventDefault(); }); } loadPage();
<input maxlength="0" id="input-id">

The above code works fine for normal alphabet characters. However, when I use IME to type Japanese fullwidth character, it does not work (still can input character)

Do you know where is the problem, and is there anyway to workaround?

10
  • 1
    EventObject.preventDefault() belongs to the EventObject, not the Element. The EventObject is passed to the EventListener when an Event occurs, like el.onkeyup = function(eventObj){ eventObj.preventDefault(); }. My guess is you really want readonly='readonly' as an HTML attribute, in this case. Commented Oct 1, 2019 at 4:19
  • If you want disabled input with cursor use this, <input maxlength="0" id="input-id" disabled syle="cursor: pointer;"> Commented Oct 1, 2019 at 4:21
  • 1
    @CertainPerformance: I am sorry, the original code was incorrected. I corrected the code Commented Oct 1, 2019 at 4:21
  • Thanks, that makes sense. Sounds like the issue is that the browsers use different methods to insert the characters - if keydown doesn't cut it, you probably need to add the listener for other related events too. (input? keyup? keypress? Try it, one of those might do it for you) Commented Oct 1, 2019 at 4:26
  • 1
    To do this with Javascript, you need to somehow identify which event that results in the added character is being fired, you could consider adding listeners via stackoverflow.com/questions/1599216/… Commented Oct 1, 2019 at 4:39

1 Answer 1

0

For IME specific events, take a look at Composition Event Types specification. Basically, there are three events handy for what you need compositionstart, compositionupdate and compositionend.

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

1 Comment

Cancelling composition events actually do not work. beforeinput should be used instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.