1

Trying to figure out how to type (via events not set the value) on an input box for IE8 and 9. I looked at some of the examples on the web - but couldn't get any of they to work. (I don't want to rely on jQuery of other libraries).

Here is what I have so far:

<form>
  <input type="text" id="txtfld" /> 
  <input type="button" onclick="typeKey()" /> 
</form>
<script>

function typeKey(){
    var  txtField = document.getElementById('txtfld');
    var evt= document.createEventObject();
    evt.keyCode=68;
    txtField.fireEvent('onkeypress', evt);
}
</script>

It does not work, and it does not give an error either.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
GeorgeU
  • 7,819
  • 8
  • 26
  • 38

1 Answers1

0

Try this function, fire(document.getElementById('txtfld'),'keypress',68):

function fire(el,evttype,code) {
   if (document.createEvent) {
     var evt = document.createEvent('HTMLEvents');
     evt.initEvent( evttype, false, false);
     evt.charCode= evt.keyCode = code;
     el.dispatchEvent(evt);
   } else if (document.createEventObject) {
     var evt = document.createEventObject();
     evt.charCode= evt.keyCode = code;
     el.fireEvent('on' + evttype, evt);
   }
}

here an example

good luck :)

Martin Borthiry
  • 5,256
  • 10
  • 42
  • 59
  • The code is missing the definition of evt for the "document.createEventObject" case. Even when defining it as: var evt = document.createEventObject; it still does not work – GeorgeU Jun 18 '12 at 15:47
  • You were right, I forgot to call createEventObject *and pass the evt*. See now the code, I'd tried the example on IE and it's working fine. – Martin Borthiry Jun 18 '12 at 16:16
  • Are you trying the last example? http://jsfiddle.net/HfU6Q/4/ ? What do you see when you press go button? can i see your code and how are you implementing this function? – Martin Borthiry Jun 19 '12 at 18:23
  • Actually i tis working.. i was just expecting the textbox would also pick the value, but it is not. – GeorgeU Jun 25 '12 at 23:55