最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how can i retrieve a current value of textarea? - Stack Overflow

programmeradmin1浏览0评论

Problem : So I have alerted the value of textarea by:

var source = document.getElementById('source').value;
            alert(source);

But the value of textarea is alerted as it was at the time of page load. And I want to alert current value of the textarea. I have also tried

$("form").submit(function(){

But that also haven't helped me. So how can I do this?

This is my code.

<html>
    <head>
    <title>Perl WEB</title>
    <script type="text/javascript" src=".js"></script>
    <link rel="stylesheet" href=".css" type="text/css" media="screen" />
    <script src=".10.2.min.js"></script>
    <script type="text/javascript" src=".js"></script>
    <style>
    .CodeMirror {
    border: 1px solid #eee;
    }   
    .CodeMirror-scroll {
    height: auto;
    overflow-y: hidden;
    overflow-x: auto;
    }
</style>
<script>
$(document).ready(function(){
  $("form").submit(function(){
    alert("Submitted");
  });
});
</script>
<script type="text/javascript">

    function execute() {
            p5pkg.CORE.print = function(List__) {
                var i;
                for (i = 0; i < List__.length; i++) {
                  document.getElementById('print-result').value += p5str(List__[i])
                }
                return true;
            };
            p5pkg.CORE.warn = function(List__) {
                var i;
                List__.push("\n");
                for (i = 0; i < List__.length; i++) {
                    document.getElementById('log-result').value += p5str(List__[i]);
                }
                return true;
            };
            p5pkg["main"]["v_^O"] = "browser";
            p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
            p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";

            var source = document.getElementById('source').value;
            alert(source);
            var pos = 0;
            var ast;
            var match;
            document.getElementById('log-result').value   = "";
        //  document.getElementById('js-result').value    = "";
            document.getElementById('print-result').value = "";
            try {
                // pile
                document.getElementById('log-result').value += "Compiling.\n";
                var start = new Date().getTime();
                var js_source = p5pkg["Perlito5"]pile_p5_to_js([source]);
                var end = new Date().getTime();
                var time = end - start;
                document.getElementById('log-result').value +=  "Compilation time: " + time + "ms\n";
        //      document.getElementById('js-result').value  += js_source + ";\n";

                // run
                start = new Date().getTime();
                eval(js_source);
                end = new Date().getTime();
                time = end - start;
                document.getElementById('log-result').value += "Running time: " + time + "ms\n";

                p5pkg.CORE.print(["\nDone.\n"]);
            }
            catch(err) {
                document.getElementById('log-result').value += "Error:\n";
                document.getElementById('log-result').value += err + "\n";
                document.getElementById('log-result').value += "Compilation aborted.\n";
                  }
        }
    </script>
    </head>
    <body>
    <form>
<textarea id="source" cols="70" rows="10">
say 'h';
</textarea>
    <div class="hint">This code is editable. Click Run to execute.</div>
    <input type="button" value="Run" onclick="execute()"/></br>
Output:</br>
    <textarea id="print-result" disabled="true" rows="10" cols="70"></textarea></br>
Log:</br>
    <textarea  id="log-result" disabled="true" cols="70"></textarea>
    <script>
      var editor = CodeMirror.fromTextArea(document.getElementById("source"), {
        lineNumbers: true,
        indentUnit: 4,
        indentWithTabs: true,
        enterMode: "keep",
        tabMode: "shift"
      });
    </script>
</form>
    </body>
</html>

So how can I get the current value of the textarea? Please help me guys.

Problem : So I have alerted the value of textarea by:

var source = document.getElementById('source').value;
            alert(source);

But the value of textarea is alerted as it was at the time of page load. And I want to alert current value of the textarea. I have also tried

$("form").submit(function(){

But that also haven't helped me. So how can I do this?

This is my code.

<html>
    <head>
    <title>Perl WEB</title>
    <script type="text/javascript" src="http://code.guru99./Perl1/codemirror.js"></script>
    <link rel="stylesheet" href="http://code.guru99./Perl1/codemirror.css" type="text/css" media="screen" />
    <script src="http://code.jquery./jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="http://code.guru99./perl/perl.js"></script>
    <style>
    .CodeMirror {
    border: 1px solid #eee;
    }   
    .CodeMirror-scroll {
    height: auto;
    overflow-y: hidden;
    overflow-x: auto;
    }
</style>
<script>
$(document).ready(function(){
  $("form").submit(function(){
    alert("Submitted");
  });
});
</script>
<script type="text/javascript">

    function execute() {
            p5pkg.CORE.print = function(List__) {
                var i;
                for (i = 0; i < List__.length; i++) {
                  document.getElementById('print-result').value += p5str(List__[i])
                }
                return true;
            };
            p5pkg.CORE.warn = function(List__) {
                var i;
                List__.push("\n");
                for (i = 0; i < List__.length; i++) {
                    document.getElementById('log-result').value += p5str(List__[i]);
                }
                return true;
            };
            p5pkg["main"]["v_^O"] = "browser";
            p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
            p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";

            var source = document.getElementById('source').value;
            alert(source);
            var pos = 0;
            var ast;
            var match;
            document.getElementById('log-result').value   = "";
        //  document.getElementById('js-result').value    = "";
            document.getElementById('print-result').value = "";
            try {
                // pile
                document.getElementById('log-result').value += "Compiling.\n";
                var start = new Date().getTime();
                var js_source = p5pkg["Perlito5"].pile_p5_to_js([source]);
                var end = new Date().getTime();
                var time = end - start;
                document.getElementById('log-result').value +=  "Compilation time: " + time + "ms\n";
        //      document.getElementById('js-result').value  += js_source + ";\n";

                // run
                start = new Date().getTime();
                eval(js_source);
                end = new Date().getTime();
                time = end - start;
                document.getElementById('log-result').value += "Running time: " + time + "ms\n";

                p5pkg.CORE.print(["\nDone.\n"]);
            }
            catch(err) {
                document.getElementById('log-result').value += "Error:\n";
                document.getElementById('log-result').value += err + "\n";
                document.getElementById('log-result').value += "Compilation aborted.\n";
                  }
        }
    </script>
    </head>
    <body>
    <form>
<textarea id="source" cols="70" rows="10">
say 'h';
</textarea>
    <div class="hint">This code is editable. Click Run to execute.</div>
    <input type="button" value="Run" onclick="execute()"/></br>
Output:</br>
    <textarea id="print-result" disabled="true" rows="10" cols="70"></textarea></br>
Log:</br>
    <textarea  id="log-result" disabled="true" cols="70"></textarea>
    <script>
      var editor = CodeMirror.fromTextArea(document.getElementById("source"), {
        lineNumbers: true,
        indentUnit: 4,
        indentWithTabs: true,
        enterMode: "keep",
        tabMode: "shift"
      });
    </script>
</form>
    </body>
</html>

So how can I get the current value of the textarea? Please help me guys.

Share Improve this question edited Jul 8, 2013 at 12:30 Teemu 23.4k7 gold badges59 silver badges111 bronze badges asked Jul 8, 2013 at 9:59 user2372214user2372214 3
  • store the valus of the textarea in a variable then alert it. – Rohit Choudhary Commented Jul 8, 2013 at 10:03
  • 2 Well, when exactly do you want the value to be shown? – Aioros Commented Jul 8, 2013 at 10:04
  • You have to execute at some point later. For example as response to a user interaction, after the user changed the value. "How" to do this depends on what exactly you want. – Felix Kling Commented Jul 8, 2013 at 10:05
Add a ment  | 

5 Answers 5

Reset to default 1

I'm not familiar with CodeMirror, but what you exactly see on the screen, is not your original #source anymore. Instead there are several elements created by CodeMirror, and the original textarea is hidden.

When I look at the documentation, I found this:

var source = editor.doc.getValue();
alert(source);

Or, since you've constructed the editor object with fromTextArea() method, you can update the value of the the textarea before reading it:

editor.save();
var source = document.getElementById('source').value;           
alert(source);

Notice also what Adam has said about submitting the form. And there are invalid </br> tags in your HTML, the correct form is <br />.

Please visit at CodeMirror User Manual for the furher information.

As you have jQuery loaded you can do as follows:

var content = $('#source').val();
alert(content);

Of course, if you do it at page load, the textarea will be empty (or even uncreated). You could extract its content on form submit, as you seem to suggest.

This code will create a button that will alert the content of your textarea when clicked:

<button onclick="alert($('#source').val())">Click me</button>

Try the following inside the submit()

var textAreaVal = $("#print-result").val();
alert(textAreaVal);

Your form does not get submitted when the button in it is pressed since this is not a submit button.

This will not submit the form, and will not alert its' contents.

<input type="button" value="Run" onclick="execute()"/></br>

Add something like this in the form:

<input type="submit" value="Submit">

if yout want the value to alert when the mouse leaves the textarea you could try to add onblur="myFunction()" to the input something like: (actually if you want it on mouse leave, you can add onmouseout="myFunction()")

<textarea id="source" cols="70" rows="10" onblur="myFunction()">
    say 'h';
</textarea>


<script type="text/javascript">
    function myFunction() {
        var source = document.getElementById('source').value;
        alert(source);
    }
</script>
发布评论

评论列表(0)

  1. 暂无评论