Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute code written in codemirror textarea?

Tags:

codemirror

I have written a basic code in CodeMirror's textarea and now facing problem in executing the code written.

Below is the HTML part:

       <form id="preview-form" method="post" action="<?php echo 
        $_SERVER['PHP_SELF']; ?>">

        <textarea class="codemirror-textarea" name="preview-form-comment" 
        id="preview-form-comment">
            #include<stdio.h>
            int main()
            {
                printf("Hello World!!");

            }
        </textarea>

        <input type="test" name="testID" id="testID" value="aqsa shahid">

        <br>

        <input type="submit" name="preview-form-submit" id="preview-form-
        submit" value="Submit" onclick="test();">


        </form> 

        <div id="preview-comment"></div>

This is the function to execute code.

        function test() {
        //code goes here
        alert(document.getElementById("preview-form-comment").value);        

        var code = $(".codemirror-textarea")[0];
        var editor = CodeMirror.fromTextArea(code, {
        lineNumbers: true,
        matchBrackets: true,
        mode: "text/x-csrc",
        theme: "dracula"

        });
        CodeMirror.runMode(document.getElementById("preview-form-
        comment").value, "text/x-csrc", document.getElementById('preview-
        comment')); };
like image 370
Aqsa Shahid Avatar asked Sep 01 '25 22:09

Aqsa Shahid


1 Answers

I know you probably solved this and it's old, but i will put this in case someone else is looking for the answer

i solved this using an iframe then in js

iframe.src = "data:text/html;charset=utf-8," + encodeURI(new_textarea.value)

and it worked for me .

like image 185
Majed Ahmed Avatar answered Sep 05 '25 21:09

Majed Ahmed