We help IT Professionals succeed at work.

Inject keyboard event to textarea

zc2 asked
On HTML page I want to keep TEXTAREA controls read-only until the user starts typing characters. All other keyboard events should not change the read-only status. In my script, on the first typed character event the handler makes the control not read-only, but that character does not go to the control itself.
I tried to do the following:
$(".textarea").keyup( function(ev) {
    var k = ev.keyCode;
    var inp = ev.target;
    if(  inp.readOnly && k >= 42 && k <= 90 ) {  // an alphanumeric
    	inp.readOnly = false;
        inp.select();  // without this IE do not accept typed in characters at all
        // i tried this:
    	var sev = $.Event("keypress", {keyCode: k, which: k});
        // and that:
    	var sev = $.Event("keypress", ev);
} );

Open in new window

Whatever I tried, the first typed character is lost, the second goes to the control.
Watch Question

Can I ask why?  What the underlying purpose is?
Just a bit confused as to why you have them as readonly, hence "unable to type into it", until they start typing into it?
In any case, changing to keydown should do what you need, you won't have to inject anything.


I am implementing a spreadsheet-like data editing page. I searched for some existing implementations on the internet and those I found do not satisfy our needs. The user is supposed to be able to freely navigate through the grid of textarea elements with the arrow keys.
Ah, I get it.
So as per above then, is there any reason you can't just use keydown?  That should work properly for what you need.


Thank you very much! The keydown handler works perfectly and I don't even need to inject the keypress event.
Most Valuable Expert 2017
Distinguished Expert 2019

What is it you are trying to do?
Can you give us a context.

TEXTAREA controls - what are those


I explained my goal in a previous comment.
textarea are those: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea