Main Page

Retrieving/changing a text box value

allowed in the text box. So to create a text box that can display 25 characters at a time but has a maxi-
mum length of 50, the following code can be used:
<input type=”text” size=”25” maxlength=”50” value=”initial value” />
element always renders a multiline text box. To specify how large the text box should
be, you can use the
attribute, which specifies the height of the text box in number of characters,
and the
attribute, which specifies the width in number of characters (similar to
for an
element). Unlike
, the initial value of a
must be enclosed between
, as shown here:
<textarea rows=”25” cols=”5”>initial value</textarea>
Also unlike the
element, a
cannot specify the maximum number of characters
Retrieving/changing a text box value
Even though they are different elements, both
<input type=”text”/>
support the
same property,
, to retrieve the text contained in the text box. Consider the following example:
<title>Retrieving a Textbox Value Example</title>
<script type=”text/javascript”>
function getValues() {
var oTextbox1 = document.getElementById(“txt1”);
var oTextbox2 = document.getElementById(“txt2”);
alert(“The value of txt1 is \”” + oTextbox1.value + “\”\n” +
“The value of txt2 is \”” + oTextbox2.value + “\””);
<input type=”text” size=”12” id=”txt1” /><br />
<textarea rows=”5” cols=”25” id=”txt2”></textarea><br />
<input type=”button” value=”Get Values” onclick=”getValues()” />
This example displays two text boxes, a single-line and a multiline, as well as a button. When you click
the button, an alert is displayed showing the values contained in each text box. Try typing into each text
box a couple of times and then click the button.
Because the value property is a string, you can use all the properties and methods of a string. For exam-
ple, you can get the length of text inside a text box by using the
<title>Retrieving a Textbox Length Example</title>
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 343

JavaScript EditorFree JavaScript Editor     Ajax Editor