限制输入字段中的字符 [英] Restrict characters in input field

查看:67
本文介绍了限制输入字段中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在输入字段中输入时,是否有任何选项可以使用此代码而不显示字母或字符?这是我已经尝试的代码,我想保留它但是现在当我在输入中写限制字符时它会显示它们。我需要将输入保持空白

is there any option to use this code without showing the letters or characters when user type in input fields? this is the code i already tried and i want to keep it but now when i write restricted chars in input it show them for a second.I need to keep the input blank

编辑:我不想更改代码,因为这在平板电脑上很有效(其他限制字符函数不会)。唯一的问题是延迟你按限制字符

i dont want to change the code because this work great on tablets (other restrict character functions doesnt) . The only problem is that delay wehn you press restricted chars

代码:

function checkInput(ob){
    var invalidChars = /[^0-9]/gi
            if(invalidChars.test(ob.value)) {
                    ob.value = ob.value.replace(invalidChars,"");
          }
};

HTML:

<input class="input" maxlength="1" onChange="checkInput(this)" onKeyup="checkInput(this)" type="text" autocomplete="off"/>


推荐答案

你可以试试这个,

$('.input').keyup(function () {
    if (!this.value.match(/[0-9]/)) {
        this.value = this.value.replace(/[^0-9]/g, '');
    }
});

看到这个有趣的演示

更新:

您可以尝试此代码,

$(document).ready(function() {
    $(".input").keydown(function (e) {
        // Allow: backspace, delete, tab, escape and enter
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) || 
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
});

消息来源

看到更新的FIDDLE DEMO

更新为ANDROID:

<EditText
android:id="@+id/editText1"
android:inputType="number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="58dp"
android:layout_toRightOf="@+id/textView1"
android:maxLength="1" >
</EditText>

我认为它可以帮助你...使用 android:inputType =数字你可以这样做。

I think it may help you... using android:inputType="number" you can do that.

这篇关于限制输入字段中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆