I want to set a 'hot key' for the Save button in an ASP.NET form. I wanted to use CTRL+S, but it seems to be the default Save 'hot key' for Windows. Is there a way to override that with my own implementation ?
-
ASP.NET is not relevant. You need to get it to work as a "hot key" (accelerator) for HTML in your chosen browsers. – John Saunders Jul 09 '14 at 10:31
-
possible duplicate of [how to replace browser short keys defaults](http://stackoverflow.com/questions/15205150/how-to-replace-browser-short-keys-defaults) – Artjom B. Jul 09 '14 at 10:36
1 Answers
This is very possible in HTML/JS. You need to assign an event handler to the element you want to "catch" the hotkeys, or event just the document as a whole.
It appears that if you use the onkeydown
event, you can circumvent the default save prompt dialog in most browsers (At least IE, Chrome, FF). I've not been able to do this using the keypress
event for example. So make sure to use the onkeydown
event!
Example:
document.onkeydown = function(event)
{
if (event.ctrlKey && event.keyCode == 83)
{
alert('You just pressed CTRL+S');
// Do stuff here
}
};
The next step is to perform the actual action you want to perform when the user presses CTRL-S. Assuming this is a standard ASP.NET web form with a postback, you can programmatically post the form.
There are multiple ways to do that, this probably being the simplest (given the document only has one form!):
document.forms[0].submit();
So the entire snippet would basically be:
document.onkeydown = function(event)
{
if (event.ctrlKey && event.keyCode == 83)
{
document.forms[0].submit();
}
};
EDIT: For multiple buttons, not just a single form submit, try something like this:
Let's say that you have these asp:buttons:
<asp:button runat="server" id="btnSaveSubmit" onclick="btnSaveSubmit_click" Text="Save and submit" />
<asp:button runat="server" id="btnSaveHold" onclick="btnSaveHold_click" Text="Save and hold" />
Then your javascript would be something like this (Note, I'm assuming you are using jQuery now):
<script>
$(function() {
document.onkeydown = function(event)
{
if (event.ctrlKey && event.keyCode == 83) //CTRL+S
{
// Just emulate a button click on the save and submit button by
// using jQuery to find the button based on it's clientID
$('#<%=btnSaveSubmit.ClientID%>').click();
}
if (event.ctrlKey && event.keyCode == 72) //CTRL+H
{
// Just emulate a button click on the save and hold button by
// using jQuery to find the button based on it's clientID
$('#<%=btnSaveHold.ClientID%>').click();
}
};
});
</script>
That should do it ...

- 13,522
- 5
- 44
- 59
-
To extend the question - i have 3 buttons : 1) Save and submit, 2) Save and Hold, 3) Cancel. I need Ctrl+S to invoke Save and Submit, Ctrl+H to invoke Save and Hold. So it is not just a submit but invoking corresponding buttons. – Chakra Jul 10 '14 at 07:23