javascript - 无法限制用户输入超过 8 个字符

标签 javascript jquery jquery-ui jquery-mobile cordova

您好,以下是我的登录表单,我想限制用户在 userName 字段中输入 8 个字符,但它不起作用,以下是我的代码:

<div data-role="content">

        <form id="loginForm">
            <div data-role="fieldcontain" class="ui-field-contain ui-body ui-br">
                <label for="username">Username:</label> <input type="text"
                    name="username" id="username" value=""   maxlength="8" /> <label for="password">Password:</label>
                <input type="password" name="password" id="password" value="" /> <label
                    for="dob">Date of birth:</label> <input type="password"
                    type="password" name="dob" id="dob" value="" />
            </div>
            <div >
                <fieldset class="ui-grid-a" >
                    <div class="ui-block-a" >
                        <input type="submit" data-role="button" value="Login"
                            id="submitButton">
                    </div>
                    <div class="ui-block-b">
                        <input type="reset" data-role="button" value="Cancel"
                            id="cancelButton">
                    </div>

                </fieldset>
            </div>
        </form>

    </div>

    <script type="text/javascript">

    </script>

    <script type="text/javascript">
        $("#username").live('keydown', function (event)
        {

            if ((event.keyCode.length>8))
            {
                event.preventDefault();
            }

        }); 

    </script>

但用户仍然可以在用户名字段中输入任意数量的字符。这段代码有什么问题?任何建议将不胜感激。提前致谢

最佳答案

在输入字段中添加一个maxlength..而不是使用脚本来限制。

<input type="text" name="username" id="username" value=""  maxlength="8" />

关于javascript - 无法限制用户输入超过 8 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11934576/

相关文章:

javascript - 在页面加载时使用 javascript(无 jquery)自行调整大小并使窗口居中

jquery - 单击事件不适用于 ckeditor、jquery 生成的动态内容

javascript - jQuery UI 模态问题

javascript - 通过拖放 DOM 元素在 d3.js 中创建形状

javascript - 火狐插件 : Access Variable in other File

javascript - 引用外部类中的 div

javascript - 在openlayers中是否有一种简单的方法来简化绘制的多边形中的顶点?

javascript - 通过选择下拉菜单更改按钮属性

javascript - 我可以在 xampp (localhost) 中运行我的项目,但即使在配置后尝试在另一台计算机中运行时我也无法运行

javascript 网页打印。在每页的页眉中打印 Logo