Usually when designing a form, we will add some hint text, for example, in the search box, we will prompt "Please enter the keyword", and in the search box to get focus and lose focus when the timely hiding and display, the most common practice is to use value to set:
Copy Code code as follows:
<form id= "Search" >
<input type= "text" id= "keyword" name= "keyword" value= "Please enter the keyword" >
<button> Search </button>
</form>
<script>
document.getElementById ("keyword"). onfocus = function () {
if (document.getElementById ("keyword"). Value = = "Please enter a keyword" {
document.getElementById ("keyword"). Value = "";
}
}
document.getElementById ("keyword"). onblur = function () {
if (document.getElementById ("keyword"). Value = = "") {
document.getElementById ("keyword"). Value = "Please enter keywords";
}
}
document.getElementById ("Search"). onsubmit = function () {
var keyword = document.getElementById ("keyword"). value;
if (keyword = = "" | | Keyword = "Please enter a keyword") {
Alert ("Please enter a keyword");
return false;
}
return true;
}
</script>
This code, while fulfilling the functionality we want, but not clean, because "please enter the keyword" Such text is only hint text, not value, although there is no technical problems, but many times it seems to be troublesome, for example, we may be like the hint text display color is gray, The text that the user types is displayed in black.
Let's look at how you can use CSS to achieve a better way:
Copy Code code as follows:
<style>
#wrapper {position:relative; display:inline;}
#description {position:absolute; left:1px; color: #999999; display:none;}
</style>
<form id= "Search" >
<div id= "wrapper" >
<label for= "keyword" id= "description" > Please enter the keyword </label>
<input type= "text" id= "keyword" name= "keyword" >
</div>
<button> Search </button>
</form>
<script>
Window.onload = function () {
if (!document.getelementbyid ("keyword"). Value) {
document.getElementById ("description"). style.display = "inline";
}
};
document.getElementById ("keyword"). onfocus = function () {
if (!document.getelementbyid ("keyword"). Value) {
document.getElementById ("description"). Style.display = "None";
}
}
document.getElementById ("keyword"). onblur = function () {
if (!document.getelementbyid ("keyword"). Value) {
document.getElementById ("description"). style.display = "inline";
}
}
document.getElementById ("Search"). onsubmit = function () {
if (!document.getelementbyid ("keyword"). Value) {
Alert ("Please enter a keyword");
return false;
}
return true;
}
</script>
This implementation, although more CSS,JS code, but the structure is more reasonable, by introducing a label to display the hint text (through the CSS position attribute positioning), so that the value itself is more simple, and prompt text and user input text in the style easier to control, such as the depth of color , which increases the availability of the form.