问题描述:

I'm trying to have a JS which has the requirement as below

I have a textbox of type number and whenever i typed inside that textbox should ONLY ALLOW numbers [0-9] and it should NOT ALLOW the length of the numbers entered to be more than 8 digits.

Eg:

12345678 - Allow

1234 - Dont Allow

1234%^ - Dont Allow

My Html:

<input type="number" id="txt_number" maxlength="8" onkeypress="return isNumber(event)">

My JS

 function isNumber(evt) {

evt = (evt) ? evt : window.event;

var charCode = (evt.which) ? evt.which : evt.keyCode;

if (charCode > 31 && (charCode < 48 || charCode > 57 ||charCode>=190)) {

return false;

}

return true;

}

Please help me.

Appreciate.

Thanks

网友答案:

please try this

 function isNumber(evt) {
 evt = (evt) ? evt : window.event;
 var charCode = (evt.which) ? evt.which : evt.keyCode;
 if (charCode > 31 && (charCode < 48 || charCode > 57)) {
     return false;
 }

 return true;

}

网友答案:
 $(function () {
    $(".numericOnly").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 (code == 8 || code == 46)
            return true;
        if (code < 48 || code > 57)
            return false;
    }
    );
    $(".numericOnly").bind("paste", function (e) {
        $("#lblSearchError").text("Phone no must be numeric digit only !!!");
        $('#lblSearchError').show('slow').delay(3000).queue(function (n) {
            $(this).hide('slow'); n();
        });
        e.preventDefault();
    });
    $(".numericOnly").bind('mouseenter', function (e) {
        var val = $(this).val();
        if (val != '0') {
            val = val.replace(/[^0-9]+/g, "")
            $(this).val(val);
        }
    });
});

with this function you can restrict user to enter other than numeric values and user won't be able to past any non-numeric data. this works for me You can use it by class name or by ID

网友答案:

Use RegEx match:

function checkMonum(){
var input=document.getElementById('txt_number').value;
    var state=false;
    var re=/^[\d\.]{8}$/;
var output = re.test(input);
if(output==true){
   state=true;
}
return state;
}

i change method match with test, you can check in FF. i am on mobile in chrome. Exactly with 8 digits or has period

相关阅读:
Top