0

I have an MVC application, and I am using Html.BeginForm to make forms. There are several forms on the page, each representing a tab in a row of tabs. I need to detect the "Enter" key being pressed on one of the tabs. Anyone know how to do this?

Code example -

<div>
@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { id = "MyForm1" }))
{
    <div id="divId">
    </div>
}
</div>

Thanks!

tereško
  • 58,060
  • 25
  • 98
  • 150
A Bogus
  • 3,852
  • 11
  • 39
  • 58
  • 1
    It's usually easiest to [use jQuery to handle that](http://stackoverflow.com/questions/699065/submitting-a-form-on-enter-with-jquery). – ataddeini Oct 05 '12 at 22:01
  • 1
    How exactly do you intent to capture the enter key on an element that does not accept keyboard input? – Erik Funkenbusch Oct 05 '12 at 22:19
  • Mystere Man, I just want to detect that the "Enter" key has been pressed. An tie the running of a specific javascript to that action. – A Bogus Oct 06 '12 at 03:57
  • Possible duplicate of [Capture an Enter Key Pressed anywhere on the page](https://stackoverflow.com/questions/7005162/capture-an-enter-key-pressed-anywhere-on-the-page) – mxmissile Dec 14 '17 at 16:01

1 Answers1

2
@using (Html.BeginForm("Create", "ApplicationSchedule", FormMethod.Post, 
        new { onkeydown = "return event.keyCode!=13" }))

You are able to add event listeners to the form using the htmlAttributes object parameter as I have done using the new { onkeydown = "return event.keyCode!=13" } section in the code. In my case I am ignoring the enter key when it is pressed in the form using the onkeydown listener. This is easily replaceable using your own code such as onkeydown = "yourJavascriptFunction()" to achive whatever it is you need to achieve when the enter key is pressed in the form. For more info on the parameters accepted for the Html.BeginForm(), see MSDN