Textarea value undefined when using getElementsByTagName

That's because you read the value when your script (which is in the HEAD of the page) is first read, before even the DOM is ready. Read the value in the function :

function displayValue() {
    var theSrc = document.getElementsByTagName('textarea')[0].value;
    alert(theSrc);
}

It is the matter where you are writing JavaScript it works fine when you write inside body tag.

<body>
--------textarea code
<script>
var theSrc = document.getElementsByTagName('textarea')[0].value;
</script>
</body>

Now it will work. That's because of document priority execution.


Either write your js after the body or use

$().ready(function(){
    //code
});

as in head is loaded before the body so, variable "theSrc" has no idea about text area

Tags:

Javascript