不允许用户输入大于12的数字

Shi*_*dam 2 javascript jquery

我有一个HTML文本框:

<input style="width: 13%; height: 25%" name="txthour" id="txthour" onkeypress="return isNumberKey(event)">
Run Code Online (Sandbox Code Playgroud)

我希望用户在输入大于12的数字时停止.

当用户输入1时,我不希望他们输入数字3,这将阻止数字变为13(大于12).

我在Javascript中用这个:

function isNumberKey(e) {

        if (isNaN($("#txthour").val()))
        {
            alert("Enter only numbers");
        }

        if ($("#txthour").val() > 12) {

            e.cancel;
        }

        }
Run Code Online (Sandbox Code Playgroud)

但如果它进入13,它就不会取消该文本.

Kar*_*non 7

您首先遇到的问题是您在keypress上绑定它.这意味着在您的活动之前$("#txthour").val() 不会更新.

您需要知道用户按下了哪个字符.有一个功能:String.fromCharCode();.

要获取当前字符,您可以使用:

var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
Run Code Online (Sandbox Code Playgroud)

然后你需要检查它是否是一个数字.

if(!isNaN(currentChar))
Run Code Online (Sandbox Code Playgroud)

然后,您需要将该字符连接到您的输入.

var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
Run Code Online (Sandbox Code Playgroud)

解析新值并检查它是否低于或等于12.如果所有这些条件匹配,则返回true.

最终代码:

function isNumberKey(e) {
    var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
    if(!isNaN(currentChar)){
        var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition

        if(parseInt(nextValue, 10) <= 12) return true;
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/6X9Yq/


编辑

要允许按Enter键,您需要检查键码是否为13:

function isNumberKey(e) {
    if(e.keyCode === 13) return true;
    var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
    if(!isNaN(currentChar)){
        var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition

        if(parseInt(nextValue, 10) <= 12) return true;
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)