Inject keyboard event to textarea

zc2
zc2 used Ask the Experts™
on
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);
    	$(inp).trigger(sev);
    }
} );

Open in new window

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

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
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.

Author

Commented:
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.
Should you be charging more for IT Services?

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

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.

Author

Commented:
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 2018

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

TEXTAREA controls - what are those

Author

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

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial