Main Page

Selecting text

<script type=”text/javascript”>
function getLengths() {
var oTextbox1 = document.getElementById(“txt1”);
var oTextbox2 = document.getElementById(“txt2”);
alert(“The length of txt1 is “ + oTextbox1.value.length + “\n”
+ “The length of txt2 is “ + oTextbox2.value.length);
}
</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 Lengths” onclick=”getLengths()” />
</body>
</html>
This example uses the
length
property of the
value
to determine how many characters are in each
text box.
The
value
property can also be used to assign a new value to a text box:
<html>
<head>
<title>Changing a Textbox Value Example</title>
<script type=”text/javascript”>
function setValues() {
var oTextbox1 = document.getElementById(“txt1”);
var oTextbox2 = document.getElementById(“txt2”);
oTextbox1.value = “first textbox”;
oTextbox2.value = “second textbox”;
}
</script>
</head>
<body>
<input type=”text” size=”12” id=”txt1” /><br />
<textarea rows=”5” cols=”25” id=”txt2”></textarea><br />
<input type=”button” value=”Set Values” onclick=”setValues()” />
</body>
</html>
In this example, clicking the button sets the first text box to
“first textbox”
and the second text box
to
“second textbox”
.
Selecting text
Both text box types support a method called
select()
, which selects all the text in the text box. In order
to work, the text box must have focus. To ensure that the text box has focus, you should always call
another method,
focus()
, before calling
select()
. (This isn’t required in all browsers, but it’s safer to
always call
focus()
first.) For example:
344
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 344


JavaScript EditorFree JavaScript Editor     Ajax Editor


©