jQuery 输入掩码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7952262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:30:41  来源:igfitidea点击:

jQuery input mask

jqueryjquery-uijquery-plugins

提问by meer

Hey, I am new to jQuery , I want to check onblur on input box this format cda 123 . mean first 3 characters space and 3 integers. Usually I see that code is written on Input id's but if I want on Class then how can I do this . For example I have class="InputMask-cccsnn" I want to have this on this format CheckInputMask(this) on class not on input id . How to change my following code . Please reply

嘿,我是 jQuery 新手,我想检查输入框上的 onblur 这种格式 cda 123 。表示前 3 个字符的空格和 3 个整数。通常我看到代码是写在 Input id 上的,但如果我想在 Class 上,我该怎么做。例如,我有 class="InputMask-cccsnn" 我想在这种格式上使用 CheckInputMask(this) 在类上而不是在输入 id 上。如何更改我的以下代码。请回复

Following is my code on keyup on one input id.

以下是我在一个输入 ID 上的 keyup 代码。

$('input').keyup(function(e){
    var value = $(this).val();
    if(value.length <= 3) {
       char = value.substring(value.length - 1);
        if(!(isNaN(char))) {
            var newval = value.substring(0, value.length - 1);
            $(this).val(newval);
        }
    }
    if(value.length > 3) {
       char = value.substring(value.length - 1);
        if(isNaN(char)) {
            var newval = value.substring(0, value.length - 1);
            $(this).val(newval);
        }
    }
});

回答by Petr

Just use some jQuery input mask plugin, for example this http://digitalbush.com/projects/masked-input-plugin/

只需使用一些 jQuery 输入掩码插件,例如这个http://digitalbush.com/projects/masked-input-plugin/

Then you can use:

然后你可以使用:

jQuery(function($){
    $(".InputMask-cccsnn").mask("aaa 999");   
});

回答by Ryan

You can use try using regular expressions.

您可以尝试使用正则表达式。

if($('input').val().match(/.{3} \d{3}$/)){
        alert('valid');
    }
    else{
        alert('invalid');
    }

Check out a sample demo for your case here

在此处查看您案例的示例演示

http://jsfiddle.net/ryan_s/WYzhR/1/

http://jsfiddle.net/ryan_s/WYzhR/1/