javascript - How to emulate a keypress for a textfield (or other inputfield) and let the browser do the default action for that keypress -


i want emulate keypress when user clicks on button. have tried of related questions on stackoverflow, nothing seems work me. in code want s appears when user clicks on button s . far 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 , addeventlistener 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>

if want character 's' come on input box when press button, append character onto 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>


Comments