How can I automatically trigger an enter keypress event after a certain action is performed?

I am writing a few unit test in my web applications, and I want to automatically trigger an event with the Enter key pressed from my page, after clicking the download button to a text file. How can I do this in jQuery or javascript?

+7
source share
4 answers
  • Create a variable that tells us if the user clicked your button.

    var clicked = false; 
  • Add an event listener to your button, so when the user clicks on it, the clicked variable will become true .

     myButton.addEventListener('click', function(){ clicked = true; }); 
  • Add a keypress event keypress :

     document.addEventListener('keypress', function(e) { // `e` is the event }); 
  • Inside this event listener, check if user clicked previously

     if(clicked) { // ... } 
  • If (s) he did, check the key pressed. Enter key code - 13.

     var keynum = e.keyCode||e.which; if(keynum == 13) { // ... } 
  • If a key is pressed, use

     clicked = false; 

    Otherwise, as soon as the user clicks your button and presses the enter key, there is no need to press the button again.

  • After that, run your code. For example, this will call f after 2 seconds.

     setTimeout(f, 2000); 

Live demo

 var clicked = false; document.querySelector('#btn').addEventListener('click', function(){ clicked = true; snippet.log("You clicked the button. `clicked` is now `true`"); }); document.addEventListener('keypress', function(e) { if(clicked) { var keynum = e.keyCode || e.which; if(keynum == 13) { clicked = false; snippet.log("`clicked` is now `false`. Waiting 2 seconds..."); setTimeout(f, 2000); } } }); function f() { snippet.log("Function `f` executed successfully!"); } 
 #btn { border: 3px solid red; cursor: pointer; } 
 <div id="btn">Click me, and then press enter.</div> <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --><script src="http://tjcrowder.imtqy.com/simple-snippets-console/snippet.js"></script> 
+7
source

If I get your question right, this is what you are looking for

 <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(document).keydown(function(event){ if(event.keyCode == 13){ alert("keypressed"); } }); function clickevent() { var e = $.Event("keydown"); e.which = 13; e.keyCode = 13; $(document).trigger(e); } </script> </head> <body id="thebody"> <input type="button" onclick="clickevent()" value="click me first"> </body> </html> 
+4
source

If you are talking about automatically entering the Enter key to fire the submit event, you can use this instead:

 $("#formID").submit(); 


To fire this event after clicking the button, try the following:
 $("#buttonID").click(function() { $("#formID").submit(); // submits form }); 
+2
source
 $("#txtfield").keyup(function(e) { if(e.keyCode == 13) { $("#submit").submit(); } }); 
+1
source

All Articles