简体   繁体   中英

Why is textarea.value returning “undefined”? (using Native Javascript)

This is really simple but I just cant figure out what is Wrong.

I got a div , a textarea , a button .

I want to use "Native-Javascript" coz lately i have been using jQuery alot and I want to go Native on this basic thing.

The Aim is to get the contents of the enter code here textarea transfered to the div and have the same logged in the console on button 's click .

See my Codes:

Javascript:

function text_func (){
    var btn = document.getElementsByTagName('button'),
        div_out = document.getElementsByTagName('div');
        txt_a = document.getElementsByTagName('textarea');

    console.log(txt_a.value);// This Logs undefined :: WHY?

        //return;
        btn[0].addEventListener('click',btn_click,false);

        function btn_click(){

            console.log(txt_a.value)//  This also logs undefined.. Why again?
            div_out.innerHTML = txt_a.value;

            }

    }

window.onload = function(){

    text_func();    

    }

HTML:

<div id="myDiv" style="width:300px; border:1px solid #ccc; height:100px; padding:10px;"></div>

<textarea style="width:300px; border:1px solid #ccc; height:100px; padding:10px;"></textarea>

<button>Go</button>

What I'm I doing wrong?....

See Fiddle: http://jsfiddle.net/3urm9/ Any Suggestion is highly appreciated.

You can try:

console.log(txt_a[0].value)

Notice the [0]

getElementByTagName

That returns an array (actually a NodeList) of elements.
Arrays don't have a value property.

You probably want to get one of the elements from the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM