Philip007
Philip007

Reputation: 3230

JavaScript getElementById().value doesn't work

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">

Upvotes: 0

Views: 12370

Answers (5)

Garis M Suero
Garis M Suero

Reputation: 8169

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>

Upvotes: 0

Philip007
Philip007

Reputation: 3230

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>

Upvotes: 0

Robusto
Robusto

Reputation: 31883

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.

Upvotes: 0

Garis M Suero
Garis M Suero

Reputation: 8169

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')">

Upvotes: 1

Pointy
Pointy

Reputation: 413709

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.

Upvotes: 7

Related Questions