Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle user hitting 'Enter' key in a ASP.NET MVC web site

I am working on a ASP.NET MVC web site that has multiple submit buttons. i.e.

    <input type="submit" name="SubmitButton" value="Reset" />     <input type="submit" name="SubmitButton" value="OK" />     <input type="submit" name="SubmitButton" value="Back" /> 

I need to allow users to quickly submitting the form by pressing the 'Enter' key. HTML standard seems to specify that the first submit button will be assumed if a user press the 'Enter' key. However, I need to make the 2nd button (i.e. the "OK") button the default button and for reasons I don't even want to talk about, changing the button order is not an option.

I googled around and I found this post about using Page.Form.DefaultButton in ASP.NET but this doesn't work with ASP.NET MVC.

I also tried the following javascript solution, while it works in Chrome but doesn't work in IE6

    $('body').keypress(function(e) {        if (e.which === 13) {           $("input[value='OK']").trigger('click');        }     }); 

I can think of some really extreme solutions such as going through every single controls in the form an attach the above function to them. However, I don't think that's a very neat solution so I am wondering has anyone got a better solution?

like image 336
oscarkuo Avatar asked Jun 24 '09 22:06

oscarkuo


2 Answers

First off, this is wrong:

<input type="submit" name="SubmitButton" value="Reset" /> <input type="submit" name="SubmitButton" value="OK" /> <input type="submit" name="SubmitButton" value="Back" /> 

All three of them are submit buttons. A reset is an input of type="reset". Get that sorted. Second of all, I've successfully implemented something like that, and it works on IE6. Try this:

    function keypressHandler(e)     {         if(e.which == 13) {             e.preventDefault(); //stops default action: submitting form             $(this).blur();             $('#SubmitButton').focus().click();//give your submit an ID         }     }      $('#myForm').keypress(keypressHandler); 

The focus() part makes the button appear to be pressed when the user presses enter. Quite nifty.

like image 73
karim79 Avatar answered Oct 11 '22 18:10

karim79


Use this.

$(function(){     $('input').keydown(function(e){         if (e.keyCode == 13) {             $("input[value='OK']").focus().click();             return false;         }     }); }); 
like image 33
jitter Avatar answered Oct 11 '22 19:10

jitter