Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea value undefined when using getElementsByTagName

Tags:

javascript

I stuck in a very simple thing that I need to do and I can't explain why is this happening. I have a textarea with no id or class or name, so the only way of selecting it with js is to use getElementsByTagName. It's the only textarea in my HTML so it's pretty obvious to use the following:

var theSrc = document.getElementsByTagName('textarea')[0].value;

However, when alerting theSrc I always get undefined. Any ideas why is this happening?

Here's the demo: http://jsfiddle.net/D3zBU/

like image 741
otinanai Avatar asked Mar 19 '13 10:03

otinanai


2 Answers

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);
}
like image 103
Denys Séguret Avatar answered Nov 16 '22 01:11

Denys Séguret


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

like image 1
A.T. Avatar answered Nov 16 '22 01:11

A.T.