简体   繁体   中英

Monaco Editor newline in getValue()

So, i'm using Monaco Editor as a big syntax-highlighted textarea which is submitted in a form with some JavaScript. To allow this to happen, I have an <input type="text" id="content" name="content" style="display: none;"> tag, and the JavaScript is connected to a button which does this:

function submitButtonClick(){
  document.getElementById("content").value = monacoeditor.getValue();
  document.getElementById("myForm").submit();
}

This works fine and does indeed submit the form, however the getValue() call appears to return the text in the monaco editor without the newlines. Text which looks like this in Monaco:

#Hello World
*I am some text*

is returned like so:

#Hello World*I am some text*

How can I ensure that I get the contents of the editor, including all of the newlines?

The problem is that HTML's <input type="text"> doesn't support line breaks. It is intended for single-line input (imagine usernames containing line breaks).

For multi-line input there is the <textarea> tag, which is just a form element like any other. Your form would then look like this:

<form id="myForm" action="..." method="POST">
    <textarea id="content" name="content" style="display: none;"></textarea>
</form>

You can then set the value of the textarea and submit the form as you did before:

function submitButtonClick () {
    document.getElementById ("content").value = monacoeditor.getValue ();
    document.getElementById ("myForm").submit ();
}

您应该使用<input type="hidden" id="content" name="content" style="display: none;">

When pulling data out of Monaco, the newlines will be /n characters. In some situations, this will not work alone as a carriage return is also required.

String.replace("\n", "\r\n");

should fix this issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM