Search code examples
javascripthtmlcodemirror

Get Codemirror textbox value on update


So I'm trying to use Codemirror to get input from a webpage and I would like it to update a value in Javascript whenever the text input changes. Currently I have this working, but the user must press a button for the input to be sent to the JS file.

<!DOCTYPE html>
<html>
    <head>
        <title>CodeMirror</title>
    <script src="codemirror/lib/codemirror.js"></script>
    <link href="codemirror/lib/codemirror.css" rel="stylesheet"></link>
    <script src="codemirror/mode/xml/xml.js"></script>
    <script src="codemirror/addon/edit/closetag.js"></script>
    <link href="codemirror/theme/dracula.css" rel="stylesheet"></link>
    </head>
    <body>
        <textarea id="editor"><p>A paragraph</p></textarea>

    <script>
        var editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
        mode: "xml",
        theme: "dracula",
        lineNumbers: true,
        autoCloseTags: true
      });

        function showCode() {
             var text = editor.getValue()
             console.log(text);
        }
    </script>

        <input id="clickMe" type="button" value="clickme" onclick="showCode();" />
    </body>
</html>

How would I be able to basically automate the button so that whenever the value of the Codemirror text area changes, the JS script runs.


Solution

  • The 'change' event will tell you when something has changed.

    const editor = CodeMirror.fromTextArea(document.getElementById('editor'), {});
    editor.on('change', (editor) => {
      const text = editor.doc.getValue()
      console.log(text);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.41.0/codemirror.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.41.0/codemirror.min.css" rel="stylesheet"></link>
    <textarea id="editor"><p>A paragraph</p></textarea>