不允许用户输入大于12的数字 [英] Don't allow the user to enter numbers greater than 12

查看:95
本文介绍了不允许用户输入大于12的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML文本框,如下:

I have an HTML textbox as:

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

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

I want user to stop if they enter a number greater than 12.

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

When the user has entered 1, I don't want to them to enter the number 3, this will prevent the number becoming 13 (which is greater than 12).

我在Java语言中将此理解为:

I am dong this in Javascript as:

function isNumberKey(e) {

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

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

            e.cancel;
        }

        }

但是如果输入13,它并不会取消文本.

But it's not cancelling the text if it enters 13.

推荐答案

您的代码的第一个问题是您在按键上绑定了它.这意味着$("#txthour").val() 将不会在您的活动之前更新.

Your first problem with your code is that you are binding it on keypress. That means $("#txthour").val() will not be updated before your event.

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

You need to know which character the user has pressed. There is a function for that: String.fromCharCode();.

要获取当前字符,可以使用以下命令:

To get the current character, you can use this:

var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);

然后您需要检查它是否为数字:

then you need to check if it is a number:

if(!isNaN(currentChar))

然后,您需要将该字符连接到输入中:

Then you need to concatenate that character to your input:

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

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

Parse the new value and check if it's less than or equal to 12. If all of these condition matches, return 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;
}

http://jsfiddle.net/6X9Yq/

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

To allow the press of the enter key, you need to check if the keycode is 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;
}

这篇关于不允许用户输入大于12的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆