2

I want to emulate a keypress when the user clicks on a button. I have tried some of the related questions on Stackoverflow, but nothing seems to work for me. In my code I want that an s appears when the user clicks on the button s . So far I have:

<!DOCTYPE HTML>
<html>
<head>

<script>
function genkey()
{
 var event = document.createEvent('Event');
 event.initEvent('keypress', true, true);
 event.keyCode = 115;
 document.dispatchEvent(event);
}

function clicked()
{
 document.getElementById('mytxt').focus();
 genkey();

}

function myattachevent(obj, eventnaam, func, useCapture)
{
 try
 {
  if (obj.attachEvent)
   obj.attachEvent('on' + eventnaam, func);
  else
   if (obj.addEventListener)
    obj.addEventListener(eventnaam, func, useCapture);
   else
    alert('both attachEvent and addEventListener do not exist!!');
 }
 catch (err)
 {
  alert('exception in myattacheevent');
 }
}

function keydownfunc(event)
{
 alert('keycode = ' + event.keyCode);
}

function initpage()
{
 myattachevent(document, 'keypress', function(event){keydownfunc(event)}, false);
}

</script>
</head>
<body onLoad="initpage();">
<INPUT type="button"  VALUE='s'  onClick="clicked() ;return false;">
<br>
<input type="text" id="mytxt" value='hi' size=10 maxlength=10>
<br>
</body>
</html>
Danny
  • 39
  • 2
  • Possible duplicate of [Simulate JavaScript Key Events](http://stackoverflow.com/questions/596481/simulate-javascript-key-events) – synthomat Aug 01 '16 at 11:34

1 Answers1

2

If you want just the character 's' to come on the input box when you press the button, you could just append the character onto the input box

 function clicked(){
     document.getElementById('mytxt').value += 's';
    }
  <INPUT type="button"  VALUE='s'  onClick="clicked();return false;">
    <br>
    <input type="text" id="mytxt" value='hi' size=10 maxlength=10>
    <br>
Jay Ghosh
  • 674
  • 6
  • 24
  • The answer of Jay Ghost is not really what I had in mind. I feel the changes to the inputfield (or in case I simulate the TAB key, the cursormove) should be done by the browser. Essentially the default action of the browser should be performed. – Danny Aug 04 '16 at 09:18
  • I also tried answers of the "Simulate JavaScript Key Events" question. I can't get any of them working, maybe I'm missing something, but none of the answers contains a complete working html page. – Danny Aug 04 '16 at 09:24
  • I saw this today, and hey! I'm not a ghost! Lol – Jay Ghosh Jun 08 '20 at 09:41