How do I restrict an input to only accept numbers?

前端 未结 17 1247
感情败类
感情败类 2020-12-07 09:28

I am using ngChange in AngularJS to trigger a custom function that will remove any letters the user adds to the input.



        
17条回答
  •  感动是毒
    2020-12-07 10:25

    All the above solutions are quite large, i wanted to give my 2 cents on this.

    I am only checking if the value inputed is a number or not, and checking if it's not blank, that's all.

    Here is the html:

    
    

    Here is the JS:

    $scope.CheckKey = function () {
        if (isNaN(event.key) || event.key === ' ' || event.key === '') {
            event.returnValue = '';
        }
    };
    

    It's quite simple.

    I belive this wont work on Paste tho, just so it's known.

    For Paste, i think you would need to use the onChange event and parse the whole string, quite another beast the tamme. This is specific for typing.

    UPDATE for Paste: just add this JS function:

    $scope.CheckPaste = function () {
        var paste = event.clipboardData.getData('text');
    
        if (isNaN(paste)) {
            event.preventDefault();
            return false;
        }
    };
    

    And the html input add the trigger:

    
    

    I hope this helps o/

提交回复
热议问题