Search code examples
javascriptjquerywindowshotkeysprompt

JQuery- hotkeys and windows prompt issue


By referring to this link I try to implement this powerful tool and facing some issue.

Every time when I click Ctrl S, it will popup a window prompt asking me whether I want to save my testing.html.

I want to ignore windows prompt.

What I want is simple:

  1. when people click save button/ use shortcut key ctrl s from keyboard

  2. script need to do a Create() checking

  3. if true then continue to submit form, if false, then stop alert Please enter question, focus back to txtQuestion, and don't do any further action.

Below is the full source code for reference: enter

   <html>
   <head>
       <style>
           * {font-family: Helvetica, Verdana, Arial; font-size:0.95em}
           .eventNotifier{width: 100px; float: left; color:navy; 
                 border: dotted 1px navy; padding: 4px; background-color:white; 
                 margin:3px}
           .dirty{border: solid 1px #0ca2ff; color:white; 
                  background-color:#0ca2ff}
       </style>
   
       <script src="jquery-1.3.2.min.js"></script>
       <script src="jquery.hotkeys-0.7.9.min.js"></script>
       <script type="text/javascript">
           $(document).ready(function() {

//weird- I found the alert Ctrl+S to appear twice.. ???
$(window).keypress(function(event) {
 if ((event.which == 115 && event.ctrlKey)){
     alert("Ctrl+S pressed");
     event.preventDefault();
 }
});

               jQuery(document).bind('keydown', 'Ctrl+s',
                      function(evt){ Create(); return false; });
               //jQuery(document).bind('keydown', 'Ctrl+s',
                     //function (evt){jQuery('#_Ctrl_s'); return false; });
           });
       
           function Create()
           {
               var f = document.frm
       
               if (f.txtQuestion.value.length == 0)
               {
                   alert('Please enter Question.')
                   f.txtQuestion.focus()
                   return false
               }
               f.submit()
           }
   
       </script>
   </head>
   <body> 
       <form name="frm" method=post action="" >
         <div id="_Ctrl_s" class="eventNotifier">Ctrl+s</div>
         <input type=text name="txtQuestion" maxlength="255" 
                   class="field400" value="">
         <input type=button value="Save" name="BtnSave" onclick="Create()" 
                   class=text100>
       </form>
   </body>
   </html>

code here


Solution

  • To avoid showing the browser Save As dialog, you must prevent the default event action, example in plain jQuery:

    $(window).keypress(function(event) {
      if ((event.which == 115 && event.ctrlKey)){
          alert("Ctrl+S pressed");
          event.preventDefault();
      }
    });