How to get the value of Codemirror textarea

JavascriptCodemirror

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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).

Solution 2 - Javascript

This works fine for me.

editor.getValue()

Solution 3 - Javascript

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();

Solution 4 - Javascript

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")

Solution 5 - Javascript

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'))

Solution 6 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNitin KabraView Question on Stackoverflow
Solution 1 - JavascriptEric LeschinskiView Answer on Stackoverflow
Solution 2 - JavascriptSiddhartha MukherjeeView Answer on Stackoverflow
Solution 3 - JavascriptSatya PendemView Answer on Stackoverflow
Solution 4 - JavascriptpmeView Answer on Stackoverflow
Solution 5 - JavascriptMohammad RezaView Answer on Stackoverflow
Solution 6 - JavascriptAlex SlovokianView Answer on Stackoverflow