ptg16476052
512 LESSON 18: Using jQuery
<label>Email address: <input name="email" value="[email protected]"
size="40" /></label>
</form>
<script src="jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function () {
$("input[name='email']").focus(function () {
if ($(this).val() == "[email protected]") {
$(this).val("");
$(this).css("color", "black");
}
});
$("input[name='email']").blur(function () {
if ($(this).val() == "") {
$(this).val("[email protected]");
$(this).css("color", "#999");
}
});
});
</script>
</body>
</html>
Again , I use two event handlers in this example. The event handlers are new, as is the
selector. Here’s one of them:
$("input[name='email']").focus(function () {
In this case, I’m using a selector that’s based on an attribute value. It matches an input
field in which the name attribute is set to email, and it binds to the focus event. This
event fires when the user places the cursor in that field. The event handler for the focus
event does two things: sets the value of the field to an empty string, and changes the
color from gray to black, but only if the value is [email protected]. If it’s something
else, it’s a value the user entered and should be left alone. Figure 18.9 shows what the
form looks like when the user initially clicks in the field.
The other event handler is bound to the blur event, which fires when the cursor leaves
the field. If the field has no value, it changes the color back to gray and puts the example
input back into the field.