How to allow only numeric (0-9) in HTML inputbox using jQuery?

前端 未结 30 1876
一生所求
一生所求 2020-11-21 05:38

I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9.

How can I do this using jQuery

30条回答
  •  忘掉有多难
    2020-11-21 06:10

    I came to a very good and simple solution that doesn't prevent the user from selecting text or copy pasting as other solutions do. jQuery style :)

    $("input.inputPhone").keyup(function() {
        var jThis=$(this);
        var notNumber=new RegExp("[^0-9]","g");
        var val=jThis.val();
    
        //Math before replacing to prevent losing keyboard selection 
        if(val.match(notNumber))
        { jThis.val(val.replace(notNumber,"")); }
    }).keyup(); //Trigger on page load to sanitize values set by server
    

提交回复
热议问题