Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple text-areas being added after an update event

I am making a simple code editor using codemirror. I am at the last stage but a bug has occurred which I am not able to get my heads around.

I have a select html tag with three options:

<select class="language" id="lang" onclick="update()">
  <option value="javascript">JavaScript</option>
  <option value="python">Python</option>
  <option value="python">C</option>
</select>

And my update() function is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function update() {
  var select = $('#lang').val();
  var editor = CodeMirror.fromTextArea($('#text'), {
      mode: select,
      theme: "blackboard",
      });
}
update();

Now what happens is that everytime I select a different option from the dropdown, a new Code editor is added below the previous one.

Do you have some idea where I am going wrong in the code and how I can workaround?

>Solution :

Change your JS to this:

let editor;
function update() {
  var select = $('#lang').val();
  editor = editor ?? CodeMirror.fromTextArea($('#text'), {
      theme: "blackboard",
  });
  editor.setOption('mode', select);
}
update();

This makes it so if editor already exists, it is not created again, but instead re-used.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading