trigger a HTML button when you press Enter

后端 未结 2 574
天命终不由人
天命终不由人 2021-01-16 03:50

I am trying to make a button key \"trigger\" on a specific page using tampermonkey. Instead of using mouse click every time to click Button called \"continue\".

So w

相关标签:
2条回答
  • 2021-01-16 04:25

    You can add autofocus attribute to button, but I'm not sure if this will work with tampermonkey. Because I think it need to be in html when page load.

    You can also use this:

     document.querySelector('[type="submit"]').focus();
    

    it will give focus to button and you will be able to submit the form with space or enter. But this if you click outside of the button you will not be able to press enter to submit the form. If you need to do some action then you can add this focus after user do something. You can also add focus when you click on document.

    var button = document.querySelector('[type="submit"]');
    window.addEventListener('click', function() {
       button.focus();
    });
    
    0 讨论(0)
  • 2021-01-16 04:37

    USING JQUERY

    You can use easy jQuery to achieve it.
    Just add a cdn given below in your main HTML page

     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
    

    And just open a script tags and copy paste this code.

    $(document).keypress(function(event){
    
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        $("#simplicityPayment-START").click();
    }});
    


    USING PURE JAVASCRIPT (NO EXTERNAL LIBRARY)

    EDIT 1: As don't own the website & using tampermonkey. Okay so there is another way to achieve this, that is Pure JAVASCRIPT. it requires no CDN. just Add this JAVASCRIPT.

    window.addEventListener('keyup', function (e) {
      if (e.keyCode === 13) {
         var button = document.getElementById("simplicityPayment-START");
         button.click();
      }
    }, false);
    
    0 讨论(0)
提交回复
热议问题