↑
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” />
The
<textarea/>
element always renders a multiline text box. To specify how large the text box should
be, you can use the
rows
attribute, which specifies the height of the text box in number of characters,
and the
cols
attribute, which specifies the width in number of characters (similar to
size
for an
<input/>
element). Unlike
<input/>
, the initial value of a
<textarea/>
must be enclosed between
<textarea>
and
</textarea>
, as shown here:
<textarea rows=”25” cols=”5”>initial value</textarea>
Also unlike the
<input/>
element, a
<textarea/>
cannot specify the maximum number of characters
allowed.
Retrieving/changing a text box value
Even though they are different elements, both
<input type=”text”/>
and
<textarea/>
support the
same property,
value
, to retrieve the text contained in the text box. Consider the following example:
<html>
<head>
<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 + “\””);
}
</script>
</head>
<body>
<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()” />
</body>
</html>
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
length
property:
<html>
<head>
<title>Retrieving a Textbox Length Example</title>
343
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 343
Free JavaScript Editor
Ajax Editor
©
→