Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

javascript - Restrict characters in input field

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

EDIT: 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

Code:

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"/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can use try this,

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

SEE THIS FIDDLE DEMO

Updated :

You can try this Code,

$(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();
        }
    });
});

SOURCE

SEE UPDATED FIDDLE DEMO

UPDATED FOR 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>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...