views:

242

answers:

1

Hi

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>

Thanks in advance!

+1  A: 

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).

bobince
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

related questions