document.write from a textbox

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
finchamgroves
Forum Newbie
Posts: 11
Joined: Wed Oct 07, 2009 10:02 am

document.write from a textbox

Post by finchamgroves »

I'm pretty new to JavaScript and struggling with document.write
It's possible to create a response box to collect data and then use document.write to return this to the existing page.
Is it possible to similarly collect data from a textbox and add that without the page reloading and losing the existing html, stylesheets etc?
e.g. As a trivial example, can I use document.write to add this to the existing body or do I have to use an innerhtml call to do this?
<head>
<script type="text/javascript">
function getText()
{
var mytext = document.getElementById('input1');
document.write(mytext.value);
}
</script>
</head>
<body>
<input type="text" name="input1" id="input1" onblur="getText()" >
</body>

I'm also struggling to understand when and why you sometimes, but not always, seem to need to add .value after the variable as in (mytext.value)
Any advice very welcome!
J
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: document.write from a textbox

Post by kaszu »

Use innerHTML.

Code: Select all

document.body.innerHTML = mytext.value;
Also you should escape the value to prevent HTML tags from being inserted into DOM.
why you sometimes, but not always
mytext is an INPUT (htmlElement, not String) which has a property 'value', that's why you need to use .value
If it's an INPUT, TEXTAREA or SELECT, then you always need to use 'value' property to get value (exception would be checkbox and radio buttons, where it's a little more complicated).
Post Reply