Reputation: 72
Below is a sample HTML code with script tag using jquery:
<html>
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var email_def= "Enter email address";
$('input[type="email"]').attr('value', email_def).focus(function() {
if ($(this).val() == email_def) {
$(this).attr('value', '');
}
}).blur(function() {
var val = $(this).val();
if (val == '') {
$(this).attr('value', email_def);
alert(val);
alert(email_def);
}
});
});
</script>
</head>
<body>
<form>
Email: <input type="email"> <input type="submit" id="submit">
</form>
</body>
</html>
Steps to reproduce:
$(this).attr('value', email_def);
not being invoked inside the blur function.Edit: Thanks for the answers. Both, the placeholder of html5 and also replacing with the $(this).val();
line seems to be working correctly
Upvotes: 0
Views: 1534
Reputation: 4004
Rafael is correct. However, if you need it to work in browsers old enough that they don't support the placeholder attribute, just switch your value attribute setters to use the overload on val() instead. So:
$(this).val('Enter the email address') //for example
See that demonstrated below (it looked like only the one in the blur method was actually a problem.
$(document).ready(function() {
var email_def = "Enter email address...";
$('input[type="email"]').attr('value', email_def).focus(function() {
//alert('focus');
if ($(this).val() === email_def) {
$(this).val('');
}
}).blur(function() {
if ($(this).val() === '') {
$(this).val(email_def);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
Email:
<input type="email" id="emailForm" size="30" />
<input type="submit" id="submitForm" />
</form>
Upvotes: 1
Reputation: 15425
Instead of $(this).attr('value', email_def);
, consider $(this).val(email_def);
. It will behave as you've specified.
Rafael is correct to suggest using HTML's placeholder
instead, unless you have some specific need regarding Internet Explorer.
Upvotes: 2
Reputation: 7746
Use HTML5 Placeholder attribute
A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored.
<form action="<some action>">
<input type="email" id="emailForm" size="30" placeholder="Enter email address"><br>
<input type="submit" value="Submit">
</form>
Upvotes: 1