Search code examples
javascriptjqueryhtmlcodemirror

Display the textarea content in alert while using code mirror


I am trying to alert the content of the textarea which is used as code mirror on a button click. But it displays as blank. if i remove the script for code mirror, it displays the content.

I need to know what is wrong with using code mirror. It doesn't reflect the changes in the textarea.

<textarea id="code" name="code">
</textarea>
<input type="button" onClick="func()">
    <script>
      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
        lineNumbers: true
      });
function func() {
alert(document.getElementById('code').value);
}
    </script>

Please help me out.


Solution

  • You need to use the editor.getValue() programming API command to get the value from the code editor.

    input {font-family: 'Segoe UI';}
    <!-- Create a simple CodeMirror instance -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.5.0/codemirror.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.5.0/codemirror.min.js"></script>
    <textarea name="" id="myTextarea" cols="30" rows="10"></textarea>
    <input type="button" value="Code?" onclick="func();">
    <script>
      var editor = CodeMirror.fromTextArea(myTextarea, {
        lineNumbers: true
      });
      var func = function () {
        alert(editor.getValue());
      }
    </script>