tags:

views:

75

answers:

5

Is there anything wrong with the code? It's not working.

<script>
t=document.getElementById('good');
document.write(t.value);
</script>

HTML:

Type-here: <input id='good' type='text' value="my value is high">
+5  A: 

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.

Pointy
You are right. Thank you!
phil
+1  A: 

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')">
Garis Suero
I rewrite the code like you said. But then the <input> tag disappears. Why?
phil
Please review the comment below...
Garis Suero
A: 

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.

Robusto
Thanks man. I just didn't know I made the same mistake. I appreciate your answer in another post.
phil
A: 

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>
phil
document.write will overwrite the whole page when called after the page has been rendered. What exactly is it that you want to happen? Do you want the script to change the value of the text box or simply show the value in an alert box?
A: 

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:

  1. Create a new element like span or div,
  2. Create a textNode with the value to insert...
  3. 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>
Garis Suero