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?
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.
Use this.
$(function(){ $('input').keydown(function(e){ if (e.keyCode == 13) { $("input[value='OK']").focus().click(); return false; } }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With