2

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/jquery@3.2.1/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".

Anthony
  • 123
  • 7
  • Why do you need to click `reset-btn`? If `reset-btn`is calling a function, why do not call that function? – Nairi Abgaryan Sep 04 '22 at 04:04
  • @NairiAbgaryan Thanks, some constraints in the situation make me only able to do this, the quickest way. I know how to make "Esc" as clicking reset, but cannot find the answer to make clicking reset also a hit on "Esc" – Anthony Sep 04 '22 at 04:10
  • 1
    you can check this: https://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programmatically – Mohamed Khedr Sep 04 '22 at 07:43

2 Answers2

0

    $(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/jquery@3.2.1/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>
Mitali Patel
  • 395
  • 2
  • 9
0

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

Anthony
  • 123
  • 7