skip to Main Content

Is there a way to trigger the hitting of "Esc" key as well when clicking the <input type="reset"> button? ( For some reason, the existing function needs Esc to work properly. )

To be precise, the desired result is:

  1. Typing in the input field
  2. Click "Reset"
  3. Clear input + Hitting the "Esc" key

Here is the form created for example:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<form onsubmit="event.preventDefault(); myFunction();">
  <input type="text" id="quick-search" required="" />
  <input type="reset" id="reset-btn" value="Reset" />
</form>
<style>
  input#quick-search:not(:valid)~input#reset-btn {
    display: none;
  }
</style>
<script>
  $(document).keydown(function(e) {
    if (e.key === "Escape") {
      $("#reset-btn").click();
    }
  });
</script>

I know how to make "Esc" as clicking reset, but cannot find the answer to make clicking reset also comes with a hit on "Esc".

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for the comment on the question.

    The script turns out be like this:

    var esc = jQuery.Event("keypress");
    esc.keyCode = 27;
    $("#reset-btn").trigger(esc);
    

    Ref: https://stackoverflow.com/a/55102965/1468253


  2.     $(document).on('keyup', function(event) {
             if (event.key == "Escape") {
                $("#reset-btn").click();
             }
        });
     input#quick-search:not(:valid)~input#reset-btn {
            display: none;
          }
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
    <form onsubmit="event.preventDefault(); myFunction();">
      <input type="text" id="quick-search" required="" />
      <input type="reset" id="reset-btn" value="Reset" />
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search