0

I have a simple code...

   document.addEventListener('keydown', function (e)
    {
           if (e.keyCode == 13 || e.keyCode == 32)
            {
                e.preventDefault();
                $(e.target).trigger("click");
            }
});

this is working fine with keycode 32 (space), but not for keycode 13 (enter) where it always submits the form. I tried adding prevent default after reading answers to some similar questions, but it doesnt solve the issue. the form is submitted anyways after pressing enter.I am looking after a solution which can be written in the script tag; since I do not want to disturb the form tags. Also, this script(without the prevent default) was working fine till some days ago.

Su-J
  • 13
  • 1
  • 9

1 Answers1

0

Su-J, if you are using an input field to submit, then you can add an attribute somewhere like this: <input type="submit" onsubmit="return false;"/>. Or you can add it to the <form> tag <form type="post" onsubmit="return false;"/>

Edit: I'd also try keypress instead. KeyPress is raised for character keys (unlike KeyDown and KeyUp, which are also raised for noncharacter keys) while the key is pressed. This is a "higher-level" event than either KeyDown or KeyUp, and as such, different data is available in the EventArgs.

See more from answers here

Community
  • 1
  • 1
Tony M
  • 741
  • 4
  • 16
  • Thanks, but I did a little edit after looking at your answer. I am not sure of how the form is programmed, since there are no form tags in the html – Su-J Apr 05 '17 at 19:57
  • In the past I've had better success with `keypress`. I definitely recommend replacing `keydown` with `keypress` as well. Options are limited without access to the DOM element submitting the form. – Tony M Apr 05 '17 at 20:17
  • nope. Thats not working. Additionally, prevent default works for the space key but not for enter. – Su-J Apr 05 '17 at 20:28