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
2010-01-13 14:03:21
TEXTBOX_ID not NAME! (Except in broken versions of Internet Explorer)
David Dorward
2010-01-13 14:04:58
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
2010-01-13 14:06:37
oops I meant the id, I just misnamed the example. It's fixed now.
Kevin
2010-01-13 14:06:56
`type="textbox"` only works because `type="text"` is the default. It should explicitly be text rather then the nonsense textbox.
David Dorward
2010-01-13 14:18:03
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
2010-01-13 14:18:42
+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
2010-01-13 14:05:02
+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
2010-01-13 14:05:32
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
2010-01-13 14:19:19
@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
2010-01-13 14:42:49