Main Page

Text box events

<html>
<head>
<title>Select Text Example</title>
<script type=”text/javascript”>
function selectText() {
var oTextbox1 = document.getElementById(“txt1”);
oTextbox1.focus();
oTextbox1.select();
}
</script>
</head>
<body>
<input type=”text” size=”12” id=”txt1” value=”initial value” /><br />
<input type=”button” value=”Select Text” onclick=”selectText()” />
</body>
</html>
This example displays a text box and a button. When you click the button, the text in the text box is
selected.
Text box events
Both text box types support the previously mentioned form-field
blur
and
focus
events along with two
others:
change
and
select
.
?
change
— Occurs when the text box loses focus after the user changed the value (does not fire
if you change the value setting the
value
property).
?
select
— Occurs when one or more characters have been selected, either manually or by
using the
select()
method.
Note the difference between the
change
event and the
blur
event. The
blur
event fires whenever the text
box loses focus; the
change
event fires when the text box loses focus as well, but only if the text in the text
box has changed. If the text is the same and the text box loses focus, only the
blur
event is fired; if the text
has changed, the
change
event fires first, followed by the
blur
event. Try it out to better get the hang of it:
<input type=”text” name=”textbox1” value=””
onblur=”alert(‘Blur’)” onchange=”alert(‘Change’)”/>
The
select
event, on the other hand, has nothing to do with the focus of the text box. This event fires
when one or more characters are selected by the user or when the
select()
method is called. You can
experiment with it:
<input type=”text” name=”textbox1” value=”” onselect=”alert(‘Select’)”/>
Select text automatically
When a user is entering information into a traditional desktop application, it is not uncommon for the
entire contents of a text box to be highlighted when the user tabs into it. This can be accomplished on
both an input-style text box and a textarea in HTML very easily: Just add the code
“this.select()”
to
the control’s
onfocus
event handler:
345
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 345


JavaScript EditorFree JavaScript Editor     Ajax Editor


©