Disable copy paste of alphabets in text field using jquery

后端 未结 6 1739
遇见更好的自我
遇见更好的自我 2021-01-14 05:33

In my project i have text field that only take numeric value.but when I copy an alphabets using ctl+c and paste using ctl+v it will allow the alphabets in the text field.So

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 06:05

    I've updated the answer of jaychapani a bit. Here I've added support for arrow keys. and prevent pressing of % & ( keys.

        $("input").bind('keypress', function (e) {
        if (e.keyCode == '9' || e.keyCode == '16') {
            return;
        }
        var code;
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;
        if (e.which == 46)
            return false;
        if (e.which == 33 || e.which == 64 || e.which == 35 || e.which == 36 || e.which == 37 || e.which == 94 || e.which == 38 || e.which == 42 || e.which == 40 || e.which == 41)
            return false;
        if (code == 8 || code == 46)
            return true;
        if (code == 37 || code == 38 || code == 39 || code == 40)
            return true;
        if (code < 48 || code > 57)
            return false;
    });
    
    
    $("input").bind("paste", function (e) {
        e.preventDefault();
    });
    $("input").bind('mouseenter', function (e) {
        var val = $(this).val();
        if (val != '0') {
            val = val.replace(/[^0-9]+/g, "")
            $(this).val(val);
        }
    });
    

    JSFiddle Demo

    Thank you.

提交回复
热议问题