Ant wrote:
Ok, so I have a regular input textbox on my webpage and I'm trying to
work out how to make it so when the user presses a button the the textbox
holds the value of a variable. I just can't work out how to do this.
any help much appreciated
That textbox - like all the HTML elements on your webpage (and many
other items as well) is represented in the (java)scripting environment
by an object. This is a software construct that provides the interface
('control panel') for programming the textbox itself. So...first, you
need to get a legitimate reference (something like a pointer) to that
object.
HTML:
<form name="a_form">
<input type="text" id="a_tbox" name="a_tbox" value="" />
JS:
var tbox = document.getElementById('a_tbox'); //uses id
....or
var tbox = document.forms['a_form'].elements['a_tbox']; //uses name
There are numerous other ways, but these are probably the commonest,
cross-browser. That (INPUT) object you just found has a .value property
- basically a read/write variable 'attached' to it, which holds the
currently displayed text string. To alter it, just assign that
variable:
var txt = 'some text';
var tbox = document.getElementById('a_tbox');
if (tbox)
{
tbox.value = txt;
}
Now all you need is to trigger the process from an event handler, in
this case the 'onclick' handler of the button you're using:
<input type="button" name="btn" value="write it" onclick="writeit()" />
What's 'writeit()'? It's the function where you 'stored' the above
instructions (statements):
function writeit()
{
var txt = 'some text';
var tbox = document.getElementById('a_tbox');
if (tbox)
{
tbox.value = txt;
}
}
Declare the function in a <script></script> block in the <head>er of
your document. It must be in memory before the button is rendered
(visible) to avoid errors.
Sorry if that's a bit pedantic, but you sound like you're just learning
this stuff. Good luck !