Page 1 of 1

document.write from a textbox

Posted: Mon Nov 09, 2009 7:07 am
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

Re: document.write from a textbox

Posted: Tue Nov 10, 2009 11:47 am
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).