Dmitry
Dmitry

Reputation: 14622

How can I set the value of a CodeMirror editor using Javascript?

I try to set id4 in the following code:

<div id="id1">
    <div id="id2">
        <div id="id3">
            <textarea id="id4"></textarea>
        </div>
    </div>
</div>

By using this code:

document.getElementById('id4').value = "...";

And this:

document.getElementById('id3').getElementsByTagName('textarea')[0].value = "...";

But nothing works.

UPDATED:

The textarea is replaced by CodeMirror editor. How do I set value to it?

Thanks a lot for the help!

Upvotes: 44

Views: 67913

Answers (7)

nelayankode
nelayankode

Reputation: 1

editor.setValue("YOUR_VALUE");

Upvotes: -1

wnm
wnm

Reputation: 1759

As you said, the textarea is replaced by Codemirror. But it is replaced by an element with the class "CodeMirror". You can use querySelector to get the element. The current CodeMirror instance (and its methods) is attached to this element. So you can do:

document.querySelector('.CodeMirror').CodeMirror.setValue('VALUE')

Upvotes: 11

fcunited
fcunited

Reputation: 180

This has worked for my (pretty old) version of CodeMirror:

var editor=CodeMirror.fromTextArea('textarea_id');

editor.setCode('your string');

Upvotes: 1

random-forest-cat
random-forest-cat

Reputation: 35894

CodeMirror ~4.6.0 you can do this, assuming you have a codemirror object:

var currentValue = myCodeMirrorObject.cm.getValue();
var str = 'some new value';
myCodeMirrorObject.cm.setValue(str);

Upvotes: 2

Ken Smith
Ken Smith

Reputation: 20445

The way to do this has changed slightly since the release of 3.0. It's now something like this:

var textArea = document.getElementById('myScript');
var editor = CodeMirror.fromTextArea(textArea);
editor.getDoc().setValue('var msg = "Hi";');

Upvotes: 77

Mariz Melo
Mariz Melo

Reputation: 850

I like examples. Try this:

CodeMirror.fromTextArea(document.getElementById(id), {
        lineNumbers: true
    }).setValue("your code here");

Upvotes: 13

Quentin
Quentin

Reputation: 943210

The code you have should work. The most likely explanation for it failing is that the elements do not exist at the time you run it. If so the solutions are to either:

  • Move the JS so it appears after the elements have been created (e.g. to just before </body>)
  • Delay execution of the JS until the elements have been created (e.g. by moving it to a function that you assign as the onload event handler)

Upvotes: 1

Related Questions