Home > Software engineering >  Submit a form only when 'enter' key is pressed
Submit a form only when 'enter' key is pressed

Time:06-17

I have an input like this which submits a form on key-up event:

<input id="filter_package_byidphrase" asp-for="@Model.FilterByPackageIdPhrase"  onkeyup="this.form.submit()">

I want the form to be submitted only when 'enter' is pressed (up). I already tried solution like this, but it didn't work:

 <input id="filter_package_byidphrase" asp-for="@Model.FilterByPackageIdPhrase"  onkeyup="keypressHandler">

 <script type="text/javascript">
      function keypressHandler(e)
      {
           if(e.keyCode == 13) {
                 e.preventDefault();
                 $('#filterform').submit();
           }
      }
 </script>

CodePudding user response:

It might be helpful to trigger the function inside the tag from the parent. Like this

<form id="myform" onsubmit="event.preventDefault()">
    <input type='text' id='input' onkeyup="keypressHandler(event)" />
</form>
<script>
    function keypressHandler(e) {
        if(e.keyCode == 13)
           myform.submit();
    }
</script>
  • Related