使用 Javascript 只允许文本框中的数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7454591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:21:48  来源:igfitidea点击:

Allow only numeric value in textbox using Javascript

javascript

提问by fawad

I want to allow only numeric values to be entered into the text and if user enters alphabetic character it should warn the user. Any suggestion for optimized and short javascript code?

我想只允许在文本中输入数值,如果用户输入字母字符,它应该警告用户。对优化和简短的 javascript 代码有什么建议吗?

回答by NimChimpsky

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

from here

这里

回答by Chamika Sandamal

use following code

使用以下代码

function numericFilter(txb) {
   txb.value = txb.value.replace(/[^
<input type="text" onKeyUp="numericFilter(this);" />
-9]/ig, ""); }

call it in on key up

按键时调用它

<input type="text" id="numbersOnly" />

回答by rlemon

Here is a solution which blocks all non numeric input from being entered into the text-field.

这是一个阻止所有非数字输入进入文本字段的解决方案。

html

html

var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
    var k = e.which;
    /* numeric inputs can come from the keypad or the numeric row at the top */
    if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
        e.preventDefault();
        return false;
    }
};?

javascript

javascript

    $(element).keydown(function (e) {
    var code = (e.keyCode ? e.keyCode : e.which), value;
    if (isSysKey(code) || code === 8 || code === 46) {
        return true;
    }

    if (e.shiftKey || e.altKey || e.ctrlKey) {
        return ;
    }

    if (code >= 48 && code <= 57) {
        return true;
    }

    if (code >= 96 && code <= 105) {
        return true;
    }

    return false;
});

function isSysKey(code) {
    if (code === 40 || code === 38 ||
            code === 13 || code === 39 || code === 27 ||
            code === 35 ||
            code === 36 || code === 37 || code === 38 ||
            code === 16 || code === 17 || code === 18 ||
            code === 20 || code === 37 || code === 9 ||
            (code >= 112 && code <= 123)) {
        return true;
    }

    return false;
}

回答by thangcao

Please note that, you should allow "system" key as well

请注意,您也应该允许“系统”键

$('#num_of_emp').keyup(function () { 
    this.value = this.value.replace(/[^0-9.]/g,'');
});

回答by soni pushkar

// Solution to enter only numeric value in text box

// 在文本框中只输入数值的解决方案

$("#testInput").keypress(function(event){

for an input box such as :

对于输入框,例如:

<input type='text' name='number_of_employee' id='num_of_emp' />

<input type='text' name='number_of_employee' id='num_of_emp' />

回答by Nadeem

@Shane, you could code break anytime, any user could press and hold any text key like (hhhhhhhhh) and your could should allow to leave that value intact.

@Shane,您可以随时中断代码,任何用户都可以按住任何文本键,例如 (hhhhhhhhh),并且您应该允许保留该值不变。

For safer side, use this:

为了安全起见,请使用:

$("#testInput").keyup(function(event){

instead of:

代替:

<input type="text" id="textBox" runat="server" class="form-control" onkeydown="return onlyNos(event)" tabindex="0" /> 


    <!--Only Numeric value in Textbox Script -->
        <script type="text/javascript">
            function onlyNos(e, t) {
                try {
                    if (window.event) {
                        var charCode = window.event.keyCode;
                    }
                    else if (e) {
                        var charCode = e.which;
                    }
                    else { return true; }
                    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                        return false;
                    }
                    return true;
                }
                catch (err) {
                    alert(err.Description);
                }
            }
        </script>
        <!--Only Numeric value in Textbox Script -->

I hope this will help for someone.

我希望这会对某人有所帮助。

回答by JIYAUL MUSTAPHA

Javascript For only numeric value in textbox ::

Javascript 仅用于文本框中的数值 ::

function isNumber(n){
  return (parseFloat(n) == n);
}

回答by Shane

or

或者

<form>
    <input type="text" id="txt" />
</form>

http://jsfiddle.net/Vj2Kk/2/

http://jsfiddle.net/Vj2Kk/2/

回答by 0x499602D2

This code uses the eventobject's .keyCodeproperty to check the characters typed into a given field. If the key pressed is a number, do nothing; otherwise, if it's a letter, alert "Error". If it is neither of these things, it returns false.

此代码使用event对象的.keyCode属性来检查输入到给定字段中的字符。如果按下的键是数字,则什么都不做;否则,如果是字母,则警告“错误”。如果这两者都不是,则返回 false。

HTML:

HTML:

(function(a) {
    a.onkeypress = function(e) {
        if (e.keyCode >= 49 && e.keyCode <= 57) {}
        else {
            if (e.keyCode >= 97 && e.keyCode <= 122) {
                alert('Error');
                // return false;
            } else return false;
        }
    };
})($('txt'));

function $(id) {
    return document.getElementById(id);
}

JS:

JS:

##代码##

For a result: http://jsfiddle.net/uUc22/

结果:http: //jsfiddle.net/uUc22/

Mind you that the .keyCoderesult for .onkeypress, .onkeydown, and .onkeyupdiffer from each other.

请注意,、 和的.keyCode结果彼此不同。.onkeypress.onkeydown.onkeyup