Hoser
Hoser

Reputation: 5044

How do I access the value of a textarea with javascript?

In one javascript function I am creating a textarea based on some JSON data I am grabbing from another site. I create the textarea here:

if(type == 'fill-in'){
    var textField = $('<center><div id="response-text"><textarea id="test" name="test" rows="10" cols="80">Answer here</textarea></div></center>').appendTo(panel.root);                        
}

In another function, I need to grab the value of this textfield and send it off to another site. I have tried this in various ways using

document.getElementById("test").value

But that gives me an error, and if I use

document.getElementByName("test").value

It tells me that the value is undefined. Do text areas not automatically set their values to whatever you type into them? Is there a better way to grab what is being typed into the textarea?

EDIT:

getElementById is working now... not sure what I was doing before but I must have tried it 3-4 times. I apologize for the pointless question.

Upvotes: 0

Views: 2626

Answers (3)

Ravi Trivedi
Ravi Trivedi

Reputation: 2360

I am assuming that Teaxarea element is loaded successfully and present in the DOM. In that case, your javascript is loading & executing even before Textarea element is loaded & ready in the DOM.

Regards,

Upvotes: 1

Chase
Chase

Reputation: 29559

Here's my best guess as to what's actually going on in your code and why you may be getting screwed over by variable hoisting.

I imagine you're trying to dynamically add your text area and then grab a reference right after by using var test = document.getElementById("test");. Because of variable hoisting, declared variables are hoisted to the top of the current scope. This would result in the declaration happening before the text area gets added.

As it is unclear where the problem lies with the OP, I did notice that you're using getElementsByName incorrectly.

getElementByName should be getElementsByName. A subtle but significant difference. Since names do not need to be unique, the function gathers a node list of all DOM elements with a given name attribute.

getElementById on the other hand returns a reference to the element itself.

getElementsByName:

Returns a list of elements with a given name in the HTML document.

getElementById:

Returns a reference to the element by its ID.

Upvotes: 1

What have you tried
What have you tried

Reputation: 11148

Using getElementById works just fine. You must have something wrong with your HTML markup - perhaps another element with the id of test.

Working fiddle:

Upvotes: 1

Related Questions