JavaScript getElementById().value doesn't work
Is there anything wrong with the code? It's not working.
<script>
t=document.getElementById('good');
docum开发者_JAVA技巧ent.write(t.value);
</script>
HTML:
Type-here: <input id='good' type='text' value="my value is high">
You're script is at the top of the document, and it runs before your input tag exists in the DOM.
Scripts execute as soon as the browser sees the </script>
closing tag. You can put your script block at the end of the <body>
or you can have the code run as an "onload" handler.
Try this:
<script>
function reWriteThis(id) {
var t=document.getElementById(id);
document.write(t.value);
}
</script>
and after, in your load tag something like:
<body onload="reWriteThis('good')">
Wait, you were just complaining in a prior question that getElementsByTagName doesn't work. In both cases, it's how you are trying to use them that isn't working.
I and others gave you comments and answers there that will enlighten you about both getElementById and getElementsByTagName.
I rewrite the code like following. But then the <input>
tag disappears. Why?
<script>
function write()
{
t=document.getElementById('good');
document.write(t.value);
}
</script>
HTML:
<body onload="write()">
Type here: <input id='good' type='text' value="my value is high" >
</body>
document.write will flush current document content.
If you want to APPEND this new content to the current content you must do something like this:
- Create a new element like span or div,
- Create a textNode with the value to insert...
- Append the new content to that element with this function : document.getElementById('theDiv').appendChild(newContent);
for example, this will work for you:
<script>
function write()
{
var t=document.getElementById('good');
if (document.createTextNode){
var mytext=document.createTextNode(t.value)
document.getElementById("newDiv").appendChild(mytext)
}
}
</script>
And here you can see the newDiv
<body onload="write()">
Type here: <input id='good' type='text' value="my value is high" >
<div id="newDiv"></div>
</body>
精彩评论