zch
zch

Reputation: 3060

How can I save the contents of a textarea as a variable using javascript in an external document?

I have tried, as many have suggested, saving a variable as the .value or .innerHTML of an ID, found by using document.getElementById. Here is all of my HTML:

<html>
<head>
<title>write</title>
<script type="text/javascript" src="g.js"></script>
<link rel="stylesheet" type="text/css" href="g.css" />
</head>

<body>
<div id="box">
    <textarea id="txt" placeholder="placeholder. type here.">text text</textarea>
</div>  
</body> 
</html>

and here is my javascript, currently meant to fire an alert that contains the text in the text area – right now that would be, text text:

function run(){
var txt = document.getElementById('txt');

alert(txt);}

run()

Right now, loading the page fires an alert with the text Null and adding .value after getElementById('txt') results in no alert. Many thanks in advance.

Upvotes: 1

Views: 21864

Answers (3)

Sibu
Sibu

Reputation: 4617

function run() {
  var txt =  document.getElementById("txt").value;

  alert(txt);
 }

 $(document).ready(function(){
            run();
 });

check this jsfiddle link

You are not getting textarea value because your javscript function is getting executed before there's value in DOM

or using javascript

function run(){
var txt =  document.getElementById("txt").value;

alert(txt);
}


window.onload = run();

More about window.onload

Upvotes: 2

Jesse
Jesse

Reputation: 5074

The problem is that your javascript is executing before the DOM is constructed. When you load the JavaScript file in the <head> of the document, it is executed immediately, before the <textarea> tag has been created.

Try moving your script block below the textarea, just before the </body> tag.

Here's an example: fiddle

After the DOM is constructed you can use getElementById just as have and can access the contents of the textarea with the value attribute. All of this is in the fiddle above.

Alternatively, you can wrap your run() method call with a library that provides an event when the DOM becomes ready. jQuery's example would be:

$(function () {
  // code you want to execute when the DOM is ready.
  run();
});

Upvotes: 4

jjm
jjm

Reputation: 6198

The javascript below works in firefox. In fact, if you click the answer button for this question, you can try it out in firebug on this very page...

var textArea = document.getElementById("wmd-input"); // #wmd-input is the text input where your answer goes...
alert( textArea.value );

Make sure you enter some text first, of course.

While you're at it, you should give jQuery a try:

alert( $("#wmd-input").val() );

Or better yet,

console.log($("#wmd-input").val());

Hope that helps.

Upvotes: 1

Related Questions