Javascript表单(建议更改但不起作用)

时间:2012-04-30 10:36:24

标签: php javascript html forms validation

嗨,阅读以前发布的建议更改但我无法看到JS工作,我没有错误有人请告诉我哪里出错了?感谢
当用户没有输入足够的字符或太多字符时,此示例场景会更改文本的颜色我还想知道是否可以将文本框的颜色更改为红色。

<script type="text/javascript">
                function checkForm()
                {
                    var username = document.getElementsById('username').value;
                    if(username.length<5)
                    {
                        alert("Username is to short");
                        return false;
                    }
                    else if (username.lenght<16)
                    {
                        alert("Username is to long");
                        return false;
                    }
                    else
                    {
                    return true;    
                    }

                }

                function checkUsername()
                {
                    var username = document.getElementsById('username').value;
                    var element = document.getElementsById('username1');
                    if(username.lenght<5)
                    {
                        element.innerHTML = "Username is to short";
                        element.style.color = "red";
                    }
                    else if (username.lenght>16)
                    {
                        element.innerHTML = "Username is to long";
                        element.style.color = "red";
                    }
                    else
                    {
                        element.innerHTML = "Valid Username";
                        element.style.color = "green";
                    }
                }

    </script>
        <p><b><h3>Welcome User Please Register</h3></b></p>
        <form action="registerUserProcess.php" id="registerUserForm" method="post" name="registerUserForm" onSubmit='return checkForm();'>

    <table> 
    <tr><td><label id="username1">Username</label></td><td><input id="username" type="text" size="16" onBlur='checkUsername();'/></td></tr>

1 个答案:

答案 0 :(得分:2)

问题在于您的标签。当您致电document.getElementById('username')时,js会在文档中搜索id == username并找到标签,而不是文本字段。将您的标签ID切换为label_username,并将id='username'添加到输入定义。