Forcing Javascript keyboard event inside a textarea on IE

I'm trying to force a keypress inside a textfield using Javascript. This has to work specifically on IE but it simply doesn't work.

Can anyone help me?

My test script is this one:

<html>
  <body>
  <input type="text" id="txtfld">
  <input type="button" onclick="go()">
  <script>
    function go() {
      var q = document.getElementById('txtfld');
      q.style.backgroundColor='yellow'; 
      q.focus();

      var evObj = document.createEventObject();
      evObj.keyCode = 84; // [T] key
      q.fireEvent('onkeypress', evObj);
    }
  </script>
  </body>
</html>
13.10.2009 17:02:14
1 ОТВЕТ
РЕШЕНИЕ

It's not a good idea to try to drive browsers' default-event-actions by faking events. In as much as it can be done at all it is browser-specific and unreliable.

If you want to add a letter ‘t’ to the field, say so:

q.value+= 't';

In more complicated cases like if you want to insert a letter at the current cursor position, you need branching code for document.selection (IE) and field.selectionStart/End (others).

2
13.10.2009 18:15:46
Thanks for answering! This is for an web automation experiment. IE fires the event over the textfield but doesn't add any content to it.
Bruno 15.10.2009 10:22:52