Well, there are couples of tutorials online to teach us, and also lots of jquery plugin for it. But I feel like I don’t need that huge functionality for this tiny thing.
So I wrote this one which is just for the little functionality.
Feature:
# default value in input box after page loaded
# on focus,
if -> input nothing -> clear to blank,
else -> keep the previous input value.
# on blur,
if -> input nothing -> back to default value,
else -> keep the previous input value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>default value for text field</title>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
</head>
<body>
<input type="text" id="inputTxt" defaultval="你在想什么..." />
<input type="button" id="submitBtn" value="提交" />
</body>
<script>
$(document).ready(function(){
var defaulval = $("#inputTxt").attr("defaultval");
var checkInputVal;
$("#inputTxt").focus(function(){
checkInputAval = checkInput("#inputTxt", defaulval);
if (checkInputAval) {
setToEmpty("#inputTxt");
$(this).css("color","#000");
}
});
$("#inputTxt").blur(function(){
checkInputAval = checkInput("#inputTxt", defaulval);
if (checkInputAval) {
setToDefault("#inputTxt", defaulval);
}
});
setToDefault("#inputTxt", defaulval);
});
function setToDefault(element, defaulval) {
$(element).val(defaulval);
$(element).css("color","#ccc");
}
function setToEmpty(element) {
$(element).val("");
}
function checkInput(element, defaulval) {
if ($.trim($(element).val()).length == 0) {
return true;
}
if ($.trim($(element).val()) == defaulval) {
return true;
}
return false;
}
</script>
</html> |
Feel free to let me know if you find some bugs or would like to give some suggestion. :]
It’s Cora’s pleasure to get information from all you guys.
++Cora++

[...] 这段文字落在Little Fox is Learning里面, 挖掘地址: http://corababy.net/tech/2009/08/07/using-jquery-to-set-default-value-of-input-box/ [...]