如何在Javascript中仅允许数字作为输入,为什么我的代码不起作用?

Die*_*ves 0 javascript

我想编写一个函数来阻止除数字0-9和返回键以外的任何输入,以便用户可以进行更正.我知道这类问题已被多次询问,但为什么我的代码不起作用.是否与shift键有关?为什么我得到"事件未定义"?

在代码片段中,我可以防止字母,但是像@这样的特殊字符会继续插入.为什么我收到参考错误?

// I have two functions 
function formatarCPF(event, controle) {
    //this line check the returned value from the functions defined below
    var eNumero = permitirApenasNumeros(event.keyCode);

    if (!eNumero)
        event.preventDefault();

    if (event.keyCode != 8) {
        var valor = controle.value;

        if (valor.length == 3) {
            controle.value = (controle.value + ".");
        }

        if (valor.length == 7) {
            controle.value = (controle.value + ".");
        }

        if (valor.length == 11) {
            controle.value = (controle.value + "-");
        }
    }
}

if(event.keyCode != 8) {
    var valor = controle.value;

    if (valor.length == 0) {
        controle.value = "(";
    }

    if(valor.length == 2) {
        controle.value = (controle.value +  String.fromCharCode(event.which)  + ")");
        event.preventDefault();
    }

    if (valor.length == 9) {
        controle.value = (controle.value + "-");
    }
}

function permitirApenasNumeros(code) {
    //checks to see if the user typed a number
    var regex = /[0-9]/;

        if(regex.test(String.fromCharCode(code)) || code == 8) {
           return true;
        } else {
           return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>


<div>
    <label for="tbCPF">CPF:</label>
    <input  onkeydown="formatarCPF(event, this)" maxlength="14" placeholder="___.___.___-__"  />
</div>
Run Code Online (Sandbox Code Playgroud)

dee*_*mar 5

试试HTML5

<input type="number" />
Run Code Online (Sandbox Code Playgroud)

或正则表达式

<input type="text" pattern="^[0-9]*$" />
Run Code Online (Sandbox Code Playgroud)