When we usually design forms, we will add some prompt text. For example, in the search box, we will prompt "Please enter keywords" and hide and display them in a timely manner when the search box gets focus or loses focus. The most common The method is to use value to set:
<script> <br>document.getElementById("keyword").onfocus = function() { <br>if (document.getElementById("keyword").value == " Please enter the keyword") { <br>document.getElementById("keyword").value = ""; <br>} <br>} <br>document.getElementById("keyword").onblur = function() { <br>if (document.getElementById("keyword").value == "") { <br>document.getElementById("keyword").value = "Please enter the keyword"; <br>} <br>} <br>document.getElementById("search").onsubmit = function() { <br>var keyword = document.getElementById("keyword").value; <br>if (keyword == "" || keyword == "Please enter keywords") { <br>alert("Please enter keywords"); <br>return false; <br>} <br>return true; <br>} <br></script>
Although such code achieves the function we want, it is not clean. The reason is that the text such as "Please enter the keyword" is just a prompt text, not a value, although technically there is no big difference. Problem, but it still seems troublesome in many cases. For example, we may make the prompt text display gray, while the text typed by the user displays black.
Let’s see how to use css to achieve a better way:
<script> <br>window.onload = function() { <br>if (!document.getElementById("keyword").value) { <br>document .getElementById("description").style.display = "inline"; <br>} <br>}; <br>document.getElementById("keyword").onfocus = function() { <br>if (!document .getElementById("keyword").value) { <br>document.getElementById("description").style.display = "none"; <br>} <br>} <br>document.getElementById("keyword") .onblur = function() { <br>if (!document.getElementById("keyword").value) { <br>document.getElementById("description").style.display = "inline"; <br>} <br>} <br>document.getElementById("search").onsubmit = function() { <br>if (!document.getElementById("keyword").value) { <br>alert("Please enter the keyword" ); <br>return false; <br>} <br>return true; <br>} <br></script>
Although this implementation requires a lot of CSS and JS code It is a little bit different, but the structure is more reasonable. By introducing label to display the prompt text (positioned through the position attribute of CSS), the value itself is simpler, and the prompt text and the text entered by the user are easier to control in style, such as the depth of the color, so that Improve form usability.