手记

html5之labels属性,自制表单验证提示

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>labels</title>
</head>

<body>
    <script>
        function Validate() {
            var txtName = document.getElementById("txt_name");
            var button = document.getElementById("btn");
            var form = document.getElementById("testform");

            if (txtName.value.trim() == "") {
                var label = document.createElement("label");
                label.setAttribute("for","txt_name");

                form.insertBefore(label,button);

                txtName.labels[1].innerHTML = "please input your name!";
                txtName.labels[1].setAttribute("style", "font-size:9px;color:red");
            }
        }
    </script>
    <form id="testform">
        <label for="txt_name"> name:</label>
        <input id="txt_name">
        <input type="button" id="btn" value="验证" onclick="Validate()">
    </form>

</body>

</html>

效果图:
点击后:

0人推荐
随时随地看视频
慕课网APP