JavaScript get TextArea input via .value or .innerHTML?
Asked Answered
C

5

60

Is it ok to get the value of a textarea element in JavaScript with myTextArea.value or should I use myTextArea.innerHTML?

Thank you.

Christo answered 15/3, 2011 at 15:42 Comment(2)
Being form element, value is the proper way.Dusky
Please, for this kind of questions always point the spec, thanks: html.spec.whatwg.org/multipage/forms.html#dom-textarea-valuePolypus
B
92

You should use .value

myTextArea.value
Burgundy answered 15/3, 2011 at 15:43 Comment(2)
Since textarea has an endtag <textarea></textarea>.I thought i have to use .innerHTML & .value won't work.I was setting textarea value in codebehind.Though innerHTML was giving me value but even though i edit the value ,it use to give me the same old value that i had setup from code behind.Read ur answer and used textarea.value.its working fine now.I'm getting textarea value properly now.up voted d ans.Sutra
Please, for this kind of questions always point the spec, thanks: html.spec.whatwg.org/multipage/forms.html#dom-textarea-valuePolypus
I
17

One difference is that you can use HTML entities with .innerHTML

document.getElementById('t1').innerHTML = '&lt;&gt;&amp;';
document.getElementById('t2').value = '&lt;&gt;&amp;';
<textarea id="t1"></textarea>
<textarea id="t2"></textarea>
Incitement answered 8/6, 2018 at 14:16 Comment(1)
This question is about reading the value, not about setting it.Conjunction
A
6

For div and span, you can use innerHTML, but for textarea use value. Please see the example below.

<script language="javascript/text">
document.getElementById("spanText").innerHTML ="text";
document.getElementById("divText").innerHTML ="text";
document.getElementById("textArea").value ="text";
</script>


<span id="spanText"></span>
<div id="divText"></div>
<textarea id="textArea"></textArea>
Audition answered 11/2, 2014 at 19:56 Comment(0)
K
1

Don't use innerHTML use value e.g. document.getElementById(name).value

Kept answered 21/10, 2017 at 21:41 Comment(0)
H
0

The answer depends on your situation.

I would personally use .value as that's what the other form inputs provide. It's easier to be in the habit of doing it that way.

Harvison answered 15/3, 2011 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.