How to get value of CodeMirror textarea [Solved]

← PrevNext →

If you using document.getElementById('text_area').innerHTML or document.getElementById('text_area').innerText to retrieve value, then these methods will not work. Here's what you should do.

Use getValue() method

Since the "textarea" element is now attached to CodeMirror editor, you'll have to retrieve data from the editor. You can use getValue() method to get (or retrieve) values.

See this example.

    <p><textarea id="ta"></textarea></p>
    let cm_editor;

    function initCodeMirror() {
        window.editor = CodeMirror.fromTextArea(document.getElementById('ta'), {
            mode: { name: "javascript", json: true },
            lineWrapping: true,
            smartIndent: true,
            addModeClass: true,
            autoCloseTags: true,
            autoRefresh: true,
            lineNumbers: true

        cm_editor = document.querySelector('.CodeMirror').CodeMirror;  // create an instance.

    window.addEventListener('load', function () { initCodeMirror(); })

    function get_textarea_value () {
        let val = cm_editor.getValue();		// retrieve values from the editor.
Try it


← PreviousNext →