javascript - Jquery Keyboard Event trigger -
i trying simulate keyboard event jquery. want when click button, want character appear in textarea. need action keyboard simulation not simple append. have tried possible solutions on web without success, grateful if can me.
here html/js/jquery code :
<html> <head></head> <body> <script type='text/javascript' src='jquery-1.9.1.min.js'></script> <input type='text' id="input"></input> <script type='text/javascript'> function simulatekeypress() { document.getelementbyid("text").focus(); var e = $.event("keypress"); e.which = 97; $("input").trigger(e); } </script> <br/> <button id="button" onclick='simulatekeypress()'>press me</button> </body> </html> as can see, when button clicked, focus on text element, no character appears, ideas?
looks not clear enough. here sample, using mousetrap library capture keyboard events. here code.
<html> <header> <title>test</title> </header> <script type='text/javascript' src='mousetrap.js'></script> <script type='text/javascript' src='jquery-1.9.1.min.js'></script> <body> <input type='text' class="mousetrap" id="input"></input> <script type='text/javascript'> mousetrap.bind('4', function(){alert("you pressed 4" );}); function simulatekeypress(character) { document.getelementbyid("input").focus(); var input = $('#input'); input.val(input.val() + character); } </script> <br/> <button type="button" onclick='simulatekeypress(4)'>press me</button> </body> </html> with code, whenever press '4' on keyboard, alert box appear. want when click button, same event created. ideas?
here 1 solution simulate keypress :
var input = $('#input'); $('#button').click(function(){ // add character input input.val(input.val() + 'x'); // trigger keypress event input.keypress(); }); // check if work input.on('keypress', function(){ alert('key pressed!'); }); here jsfiddle demo.
Comments
Post a Comment