Search code examples
javascriptjquerycodemirror

Codemirror can't use variable to get or set Value


Hello everybody I am using the Codemirror editor and have a standard code added inside the html textarea tag then I create the Codemirror element in jQuery but when I want to set the elements value from outside with setValue or getValue that doesn't work because the variable I defined codemirror to is undefined. The only workaround I found was to save the codemirror instance to a global variable using the change instance of codemirror but then the problem arises how do I trigger the change method on creation? Even better would be if the codemirror assigned variable wouldn't be undefined any suggestions?

<textarea name="mediaopt" rows="8" cols="80">/*===== MEDIA OPTIMIZATION =====*/
</textarea>
editor2 = CodeMirror.fromTextArea($('textarea[name="mediaopt"]')[0], {
                         lineNumbers: true,
                         lineWrapping: true,
                         smartIndent: true,
                         mode: "text/css",
                         extraKeys: {"Shift-Space": "autocomplete"},
                         autoCloseBrackets: true,
                         matchBrackets: true,
                         closeTags: true,
                         theme: "monokai",
                 }).on('change', editor => {
                        cssmediaopt = editor.getValue();
                        globaleditor = editor;
                });

In this case editor2 is always undefined editor inside the change function is the codemirror instance which only works once the change method has been triggered and therefore globaleditor is undefined until the change thats what I want to change :)


Solution

  • I would suggest wrapping each textarea in a div with a unique id / class. This way you can specify which codemirror instance you want to have the change event.

    Use change, where I prefer using keyup, on the .CodeMirror class.

    You can set your variables directly after an editor has been intialized.

    var editor2 = CodeMirror.fromTextArea($('textarea[name="mediaopt"]')[0], {
        lineNumbers: true,
        lineWrapping: true,
        smartIndent: true,
        mode: "text/css",
        extraKeys: {"Shift-Space": "autocomplete"},
        autoCloseBrackets: true,
        matchBrackets: true,
        closeTags: true,
        theme: "monokai",
    }
    var cssmediaopt = editor.getValue();
    var globaleditor = editor;
    
    $(document).on('change', '.Editor_2 .CodeMirror', function() {
        cssmediaopt = editor.getValue();
        globaleditor = editor;
    });