TypeError when applying a textarea's value to a variable
JavaScript
var textarea = document.g开发者_如何学JAVAetElementById("textarea").value;
HTML
<textarea id="textarea" cols="100" rows="10">du hello!</textarea>
TypeError: Result of expression
'document.getElementById("textarea")' [null]
is not an object.
This error states that it couldn't find an element with the id "textarea". The result of this getElementById
operation is therefore null
, and you can't access .value
on null
because it doesn't have any properties.
The root cause of this is that no element with the id "textarea" exists at the time of searching. Either you have a typo somewhere, or your script is running at a time when the element doesn't exist (yet). If your script is in the header, you'll want to write it like this:
document.ready = function () {
... script here ...
}
That will delay the execution until the document is ready and all elements exist.
if you are using wysiwyg editor like tinymce or else. document.getElementById("textarea").value; will not work they have there own method to get data.
<script type="text/javascript">
function test(name){
var textarea = document.getElementById("textarea").value;
alert(textarea)
}
</script>
<textarea id="textarea" cols="100" rows="10">du hello!</textarea>
<a href="javascript:void(0)" onclick="javascript:test('this is just testing')">Test TextArea</a>
精彩评论