使用 jquery 创建文本输入组合?

发布于 2024-12-04 14:03:32 字数 68 浏览 3 评论 0原文

我想知道 jquery 是否可以使文本字段只接受 3 个字母和 4 个数字的组合(例如 ABC1234) - 按这个顺序?

i was wondering whether it was possible for jquery to make a text field only accept a combination of 3 letters and 4 numbers (eg ABC1234) - in that order?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

唱一曲作罢 2024-12-11 14:03:32

http://jsfiddle.net/MEvj3/

这是一种方法的简化示例。

<input type="text" class="code" />

$("input.code").keyup(function(){
    this.value = this.value.match(/[A-Z]{3}([0-9]{1,4})?|[A-Z]{1,3}/i)[0];
});

http://jsfiddle.net/MEvj3/

Here's a simplified example of one way.

<input type="text" class="code" />

$("input.code").keyup(function(){
    this.value = this.value.match(/[A-Z]{3}([0-9]{1,4})?|[A-Z]{1,3}/i)[0];
});
孤君无依 2024-12-11 14:03:32
$("#text-input").focusout(function(){
    var regex = "[\w]{3}[\d]{4}"
    if(this.value.match(regex)){
        // display success
    }else{
        /// display error
    }
});
$("#text-input").focusout(function(){
    var regex = "[\w]{3}[\d]{4}"
    if(this.value.match(regex)){
        // display success
    }else{
        /// display error
    }
});
何以畏孤独 2024-12-11 14:03:32

如果您创建了一个带有 maxlength...

<input id="testy" type="text" maxlength="7" />

...那么您可以检查它的长度和 jQuery 的 e.which

$('#testy').keydown(function (e) {
    var keycode = e.which,
        isLetter = keycode > 64 && keycode < 90,
        isNumber = keycode > 47 && keycode < 58,
        l = this.value.length;
    if (keycode !== 8 && ((l < 4 && !isLetter) || (l > 3 && !isNumber))) {
        e.preventDefault();
    }
});

请注意,有一些陷阱:

  • 我不知道它的可移植性如何到不同的操作系统(使用 jQuery 时也许不是什么大问题)
  • 我没有数字键盘,也许这些键码不同(使用 jQuery 时也许不是什么大问题)
  • Del 按钮将老实说

,代码相当草率。它只是应该让人们理解基本的想法;您可能需要对其进行调整才能获得真正适合您的项目的东西。

If you created an input with a maxlength...

<input id="testy" type="text" maxlength="7" />

...then you could just check it's length and jQuery's e.which:

$('#testy').keydown(function (e) {
    var keycode = e.which,
        isLetter = keycode > 64 && keycode < 90,
        isNumber = keycode > 47 && keycode < 58,
        l = this.value.length;
    if (keycode !== 8 && ((l < 4 && !isLetter) || (l > 3 && !isNumber))) {
        e.preventDefault();
    }
});

Note that there are some gotchas:

  • I don't know how portable this is to different OSs (maybe not such a big deal when using jQuery)
  • I don't have a numpad, and maybe those keycodes are different (maybe not such a big deal when using jQuery)
  • The Del button will be disabled

Honestly, the code is pretty sloppy. It's just supposed to get the basic idea across; you'll probably have to tweak it to get something that really works for your project.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文