tags:

views:

35

answers:

3

Can anyone show me how to get to a text edit box in a html page and set its value using Java script please?

+4  A: 
<input type="textbox" id="ExampleTextBox" />

If you know the id of it:

document.getElementById(TEXTBOX_ID).value = YOUR_VALUE;

or in a function:

function chanageTextBoxValue(newValue)
{
   document.getElementById('ExampleTextBox').value = newValue;
}
Kevin
TEXTBOX_ID not NAME! (Except in broken versions of Internet Explorer)
David Dorward
well the post starts off "if you know the id of it". i don't think he literally meant the name-attribute of the textbox but rather "name as in that by which you identify the textbox"
David Hedlund
oops I meant the id, I just misnamed the example. It's fixed now.
Kevin
`type="textbox"` only works because `type="text"` is the default. It should explicitly be text rather then the nonsense textbox.
David Dorward
If you are using XHTML, then it is `id` not `Id`. If you are using HTML then there shouldn't be a `/` at the end.
David Dorward
+5  A: 

Given a text box

<input type="text" id="MyInput">

You Javascript would look like:

document.getElementById("MyInput").value = "some value";

There will be other ways of doing this if you are using a JavaScript framework, for example in jquery, the following will suffice:

$("#MyInput").val("some value");
James Wiseman
+1  A: 

You can access it through your form:

document.myForm.firstName.value = "Hello World";

--

<form name="myForm">
  <input type="text" name="firstName" />
</form>
Jonathan Sampson
Give forms ids, not names. (Especially in XHTML where the DTD doesn't include name attributes for forms). It is also neater to use `document.forms.myForm.elements.firstName` rather then the legacy approach which mixed form controls with all the other properties of the form (and is why `.submit` and friends can be broken by the content of forms.
David Dorward
@David: XHTML1.0 is just (with very few exceptions) the same content model as HTML4.01 restated as an XML application; as such `form name` is still valid in Transitional, but not Strict. I would certainly agree `id` is preferable though (and explicit use of the `forms` and `elements` HTMLCollections).
bobince