Search code examples
javascriptcodemirror

How to submit a form using Ctrl+S with Codemirror key bindings


I have a basic form with Codemirror implemented. I want to bind the keys Ctrl + S to submit the form. I found the Ctrl + S (extrakeys) function for Codemirror, but I have no idea what to put in there.

<form action="action.htm" method="post" id="myform">
  <textarea name="editor" id="editor" class="codemirror-area"></textarea>
  <button type="submit">Save</button>   
</form>

<script>
 var editor = CodeMirror.fromTextArea(document.getElementById("editor"), {
    lineNumbers: true,
    autoCloseTags: true,
    setSize: (200,200),
    indentWithTabs: true,
    theme: "default",   
    lineWrapping: true,         
    extraKeys: {
      "F11": function(cm) {
      cm.setOption("fullScreen", !cm.getOption("fullScreen"));
      },
      "Esc": function(cm) {
      if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
      },
      "Ctrl-S": function(instance) { 
      saveText(instance.getValue()); },
      }      
     }
   });
 </script>

Solution

    1. If you want with Codemirror.
     var editor = CodeMirror.fromTextArea(document.getElementById("editor"), {
       lineNumbers: true,
       autoCloseTags: true,
       setSize: (200,200),
       indentWithTabs: true,
       theme: "default",   
       lineWrapping: true,         
       extraKeys: {
         "F11": function(cm) {
           cm.setOption("fullScreen", !cm.getOption("fullScreen"));
         },
         "Esc": function(cm) {
          if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
        },
        "Ctrl-S": function(instance) { 
          $("#myform").submit();
        },
      }      
    });
    

    Or alternative method:

    1. First add jquery library.
    2. After add this code:
    jQuery(document).keydown(function(event) {
                if((event.ctrlKey || event.metaKey) && event.which == 83) {
                    // Save Function
                    $("#myform").submit();
                    event.preventDefault();
                    return false;
                }
            }
        );
    

    This is better :)