javascript - 使 'Go/Enter' 键可按下

标签 javascript jquery forms

我有一个基本的表单,因此用户不能在表单发布页面之前将输入字段留空。它还可以防止用户输入乱码并要求他们只输入数字,但这也会阻止所有不是数字的键,包括移动键盘上的 Go/Enter。我的问题是,有没有办法让用户只需输入数字,而且在输入字段后还可以按 Go 键?

fiddle :http://jsfiddle.net/schermerb/nX8Hx/

目前,用户必须输入一个 zip,然后在屏幕上点击返回,然后点击提交。

    $(document).ready(function () {
        $("#quantity").keypress(function (e) {
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                $("#errmsg").html("Enter Valid Zip!").show().fadeOut("5000");
                return false;
            }
        });
    });

    var initVal = "Have a good name for it? Enter Here";
    $(document).ready(function () {
        $(".submit-name").attr("disabled", "true");
        $(".recipe-name").blur(function () {
            if ($(this).val() != initVal && $(this).val() != "") {
                $(".submit-name").removeAttr("disabled");
            } else {
                $(".submit-name").attr("disabled", "true");
            }
        });
    });
input {
    width: 100%;
    background: #FFFFFF;
    border-radius: 4px;
    border: 2px solid #acd50b;
    padding: 10px 15px;
    text-align: center;
    -webkit-appearance: none;
    color: #999999;
    font-size: 11px;
}
input[type="focus"] {
    outline: none;
}
input[type="submit"] {
    border-radius: 4px;
    border: 2px solid #2d8b1b;
    -webkit-appearance: none;
    background: #acd50b;
    padding: 6px 10px;
    color: #444444;
    width: 100%;
    font-size: 18px;
    cursor:pointer;
}
.box {
    width: 85px;
}
.boxtwo {
    width: 160px;
}
<form action="google.html" method="get" id="recipename">
    <div class="box">
        <input onFocus="this.value=''" type="text" value="Enter Your Zip" placeholder="Enter Your Zip" /><span id="errmsg"></span>

    </div>
    <div class="boxtwo">
        <input type="submit" value="Compare" id="register" disabled value="Compare" class="submit-name" />
    </div>
</form>

最佳答案

最好使用 keydown 并测试结果值并将其还原,而不是只允许插入某些字符。

$("#quantity").keydown(function (e) {
    var self = this;
    var tempVal = this.value;
    setTimeout(function () {
        if (!isValidZip(self.value)) {
            self.value = tempVal;
        }
    }, 0);
});

function isValidZip(zip) {
    return /^[0-9]{1,5}$/.test(zip);
}

http://jsfiddle.net/nX8Hx/3/

这也可以通过 keyup 或 keypress 来完成,但是 keydown 使它发生得更快,并允许您轻松获得以前的值。

这样做可以避免通过不测试按下哪个键来阻止完成键的问题。它也很容易扩展,只需更改正则表达式以匹配不同类型的邮政编码。

关于javascript - 使 'Go/Enter' 键可按下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21866799/

相关文章:

javascript - 在 JQuery Mobile Slider 上指定间隔

javascript - Material UI 多选中的可删除芯片

javascript - 我可以使用自定义选择框来用Php处理元素的值吗?

javascript - 无法使用 require.js 加载 jquery

影响两个下拉菜单的javascript

javascript - jquery和ajax请求

jquery - 关于 Bootstrap 下拉菜单

c# - ASP.NET MVC 2.0 - IList<T> 复选框

javascript - 使用 ng-repeat 制作列表,以 "custom categories"分隔(AngularJS)

javascript - 如何使用 useMemo 钩子(Hook)来内存 child