Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...