Link to home
Start Free TrialLog in
Avatar of zc2
zc2Flag for United States of America

asked on

Inject keyboard event to textarea

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.
Avatar of Snarf0001
Snarf0001
Flag of Canada image

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.
Avatar of zc2

ASKER

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.
ASKER CERTIFIED SOLUTION
Avatar of Snarf0001
Snarf0001
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of zc2

ASKER

Thank you very much! The keydown handler works perfectly and I don't even need to inject the keypress event.
What is it you are trying to do?
Can you give us a context.

TEXTAREA controls - what are those
Avatar of zc2

ASKER

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