When I edit the code in a TextArea using CodeMirror how to reflect this into another textarea with js or jQuery

前端 未结 6 1076
暗喜
暗喜 2021-02-03 23:59

The App: I have a textarea element in my page. It is transformed using CodeMirror, because I need to indent and highlight html code withing it. Pic is in the li

相关标签:
6条回答
  • 2021-02-04 00:23

    Pass an onChange option to CodeMirror which looks something like this:

    onChange: function (cm) {
       mySecondTextArea.value = cm.getValue();
    }
    

    Edited to note: Since CodeMirror version 2.0, you don't pass an onChange option anymore to register a change handler, but call instance.on("change", function(cm, change) { ... }) instead. http://codemirror.net/doc/manual.html#event_change

    0 讨论(0)
  • 2021-02-04 00:23

    So you want to copy text from one TextArea (which renders as an input control, by the way) to another?

    //Set the button to call a Javascript function when it is clicked
    <button type="submit" onclick="copyText();">Post</button>
    
    <script type="text/javascript">
        function copyText() {
            //Get the text in the first input
            var text = document.getElementById("firstTextArea").getValue(); 
            //Can't use .value here as it returns the starting value of the editor
    
            //Set the text in the second input to what we copied from the first
            document.getElementById("secondTextArea").value = text;
        }
    </script>
    
    0 讨论(0)
  • 2021-02-04 00:24

    You Can Use This ...

    var editor_js = CodeMirror.fromTextArea(document.getElementById("js"), {
       mode: 'text/javascript',
       theme: 'icecoder',
       styleActiveLine: true,
       lineNumbers: true,
       lineWrapping: true,
    });
    

    And Get Data With editor_js.getValue()

    0 讨论(0)
  • 2021-02-04 00:30

    onChange handling in code mirror is not like this :

    onChange: function(cm) { mySecondTextArea.value = cm.getValue(); }
    

    you have to use :

    $.fn.buildCodeMirror = function(){
        var cmOption {...};
        var cm = CodeMirror($("MyDomObjectSelector")[0],cmOption);
        cm.on("change",$.fn.cmChange);
    }
    
    $.fn.cmChange = function(cm,cmChangeObject){
        alert("code mirror content has changed");
    }
    
    0 讨论(0)
  • 2021-02-04 00:35

    This works work CodeMirror 5.22.0:

    CodeMirror.fromTextArea(document.getElementById('grammar'), {
        lineNumbers: true,
        mode: 'pegjs',
    }).on('change', editor => {
        console.log(editor.getValue());
    });
    
    0 讨论(0)
  • 2021-02-04 00:42

    Last released version at moment (v 3.15) works with this solution:

    // on and off handler like in jQuery
    CodemirrorInstance.on('change',function(cMirror){
      // get value right from instance
      yourTextarea.value = cMirror.getValue();
    });
    
    0 讨论(0)
提交回复
热议问题