86

I am using Codemirror's plugin for textarea but I am not able to retrieve the value of textarea.

Code:

var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
    lineNumbers: true,
    matchBrackets: true,
    mode: "text/x-csrc"
  });


function showCode()
{
    var text = editor.mirror.getCode();
    alert(text);
}

It is showing the error:

editor.getCode() is not a function.
Community
  • 1
  • 1
Nitin Kabra
  • 3,146
  • 10
  • 43
  • 62

7 Answers7

107

Try using getValue() instead of getCode().

Pass in an optional argument into getValue(separator) to specify the string to be used to separate lines (the default is \n).

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
  • 1
    is there a way to get a reference to the text without calling getValue()? This function is really slow if you have a lot of text in the editor and it will lock the UI thread. – Gubatron Sep 06 '13 at 02:47
  • 2
    Is there a difference between `cm.getValue()` and `cm.doc.getValue()`? – 425nesp Aug 14 '14 at 23:16
45

This works fine for me.

editor.getValue()
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Siddhartha Mukherjee
  • 6,138
  • 3
  • 23
  • 11
7

In version 6 assuming you have your EditorView in variable editor then you do:

editor.state.doc.toString()
Grzegorz Adam Kowalski
  • 5,243
  • 3
  • 29
  • 40
6

use your_editor_instance.getValue();

It will work fine because there is no function named with the name getCode() in CodeMirror.

For setting value use your_editor_instance.setValue();

SharpC
  • 6,974
  • 4
  • 45
  • 40
Satya Pendem
  • 307
  • 5
  • 13
1

Version: 5

According to the Documentation, you need now to do it like:

doc.getValue(?separator: string) → string

So in this example:

editor.getDoc().getValue("\n")

pme
  • 14,156
  • 3
  • 52
  • 95
1

I know you are using textarea but I hope this code will be useful for others! I have this problem but with article tag, and this is my solution to getting all codes with jquery:

res_array = []
$.each($('article.code-draft span[role="presentation"]'), function(){
    res_array.push($(this).text())
});
console.log(res_array.join('\n'))
Mohammad Reza
  • 693
  • 9
  • 16
0

This works for C++ Selenium instances where you are trying to capture the text returned in a CodeMirror text area:

var myText = this.WebDriver.ExecuteJavaScript<string>("return $editor[0].getValue()");

Where [0] is the index of the code mirror text area in the form.

bananabrann
  • 556
  • 7
  • 26