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/
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With