Need to refresh the page to display file content


#1

I am using this link https://stackoverflow.com/a/44161989/10220825 to load the content of the chosen file into the textarea. It is working without doing refreshing the page. But when I am involving codemirror javascript function, it is not immediate reflecting, instead I need to do refresh to show the contents.

Without codemirror javascript function,it is working

<div>
 <label for="input-file">Specify a file:</label><br>
 <input type="file" id="input-file">
</div>

<textarea id="content-target"></textarea>

<script>
document.getElementById('input-file')
  .addEventListener('change', getFile)

function getFile(event) {
        const input = event.target
  if ('files' in input && input.files.length > 0) {
          placeFileContent(
      document.getElementById('content-target'),
      input.files[0])
  }
}

function placeFileContent(target, file) {
        readFileContent(file).then(content => {
        target.value = content
  }).catch(error => console.log(error))
}

function readFileContent(file) {
        const reader = new FileReader()
  return new Promise((resolve, reject) => {
    reader.onload = event => resolve(event.target.result)
    reader.onerror = error => reject(error)
    reader.readAsText(file)
  })
}</script>

But when I am putting codemirror javascript function just after the textarea , it is not working instead, it involves refreshing of page.

<textarea id="content-target"></textarea>
    <script>
            var editor = CodeMirror.fromTextArea(document.getElementById('content-target'),{
                     mode:"text/x-java",
                     lineNumbers:true,
                     lineSeparator: "\n",
                     autoCloseTags:true,
                     tabSize:5
                });

    </script>
    <script>
    document.getElementById('input-file')
      .addEventListener('change', getFile)
      .....

Please suugest me how to get rid of refreshing the page when codemirror mode is used.


#2

You’ll have to call setValue on the actual CodeMirror instance to update its content—changing the value of the textarea that it originated from doesn’t automatically cause the editor instance to update itself.


#3

Hi margin, I tried many times with different approach, but it is not happening. Here what I have tried:
1st approach:

var editor = CodeMirror.fromTextArea(document.getElementById('content-target'),{
                            mode:"text/x-java",
                            lineNumbers:true,
                            lineSeparator: "\n",
                            autoCloseTags:true,
                            tabSize:5
                    });
  editor.setValue(target.value=content);

2nd approach:

this.editor.setValue(content);
var that = this;
setTimeout(function() {
    that.editor.refresh();
},1);

Please suggest me correct approach and syntax to implement it. Thanks!