Can't get loadmode.js to work

Hi, I’m new to CodeMirror and I was able to get a basic CodeMirror setup working if I preset the mode, however I want the user to be able to set the mode using a dropdown select field. I tried setting this up using the loadmore.js addon, but I can’t seem to get it to work. I also don’t get any console errors.

Here is what I have so far:

<script>
CodeMirror.modeURL = "../mode/%N/%N.js";

var cm = CodeMirror.fromTextArea(document.getElementById('form-field-codesnippet'), {
    theme: "dracula",
    lineNumbers: true,
    autoCloseTags: true
});

cm.setSize("100%","400");

// Change lang
jQuery(document).ready(function ($) {
    'use strict';
    $("select#form-field-syntax").change(function(){
        var selectedLang = $(this).children("option:selected").val();
        cm.setOption("mode", selectedLang);
        CodeMirror.autoLoadMode(cm, selectedLang);
    });
});
</script>

<textarea id="form-field-codesnippet"></textarea>

<select id="form-field-syntax">
    <option value="css">CSS</option>
    <option value="xml">HTML</option>
    <option value="javascript">JavaScript</option>
    <option value="php">PHP</option>
    <option value="sql">SQL</option>	
</select>

Your use of autoLoadMode looks fine, at a glance, so I’m not sure what’s going wrong.

1 Like

Thanks marjin! Can you recommend a way to debug this?

I’d add some log statements to loadmode to see what it’s doing, I guess.

1 Like

I found the issue. It was unrelated to Code Mirror. But now that I got autoload to work, I’m facing a new issue:
When I switch the language to PHP I get the following error in console. (Switching to CSS, HTML, JS works properly).

Uncaught TypeError: Cannot read property ‘prev’ of undefined
at Object.dispatch [as token] (php.js?ver=10.5.0:187)
at readToken (codemirror.js?ver=10.5.0:1168)
at processLine (codemirror.js?ver=10.5.0:1153)
at codemirror.js?ver=10.5.0:1135
at LeafChunk.iterN (codemirror.js?ver=10.5.0:5610)
at Doc.iterN (codemirror.js?ver=10.5.0:5712)
at Doc.iter (codemirror.js?ver=10.5.0:6098)
at getContextBefore (codemirror.js?ver=10.5.0:1134)
at getLineStyles (codemirror.js?ver=10.5.0:1113)
at buildLineContent (codemirror.js?ver=10.5.0:1748)

Works now once I added the clike mode:

<script src="/codemirror/mode/clike/clike.js"></script>

Not sure why that mode has to be loaded in order for PHP to work…