Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 938
Dmitry Avatar asked Dec 04 '11 21:12

Dmitry


People also ask

How do I set up CodeMirror?

The easiest way to set up CodeMirror is via <script> tag from a CDN. You can also bundle the CodeMirror npm module, but for the sake of example let's just use a CDN. Just make sure you include both the JavaScript and CSS files, otherwise your editor won't look right.

How do I reset CodeMirror editor?

If you don't want to kill the CodeMirror instance, just change the entire document holding the text, data on markers etc. This can be done by calling cm. swapDoc(doc: CodeMirror. Doc) .

What is CodeMirror CSS?

CodeMirror is a code editor component for the web. It can be used in websites to implement a text input field with support for many editing features, and has a rich programming interface to allow further extension.


2 Answers

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";'); 
like image 65
Ken Smith Avatar answered Oct 04 '22 13:10

Ken Smith


I like examples. Try this:

CodeMirror.fromTextArea(document.getElementById(id), {         lineNumbers: true     }).setValue("your code here"); 
like image 32
Mariz Melo Avatar answered Oct 04 '22 14:10

Mariz Melo