限制对文本框的输入:只允许数字和小数点。

时间:2021-05-17 17:11:34

How can I restrict input to a text-box so that it accepts only numbers and the decimal point?

如何将输入限制为文本框,使其只接受数字和小数点?

30 个解决方案

#1


137  

<HTML>
  <HEAD>
    <SCRIPT language=Javascript>
       <!--
       function isNumberKey(evt)
       {
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;

          return true;
       }
       //-->
    </SCRIPT>
  </HEAD>
  <BODY>
    <INPUT id="txtChar" onkeypress="return isNumberKey(event)" 
           type="text" name="txtChar">
  </BODY>
</HTML>

This really works!

这确实有效!

#2


24  

form.onsubmit = function(){
    return textarea.value.match(/^\d+(\.\d+)?$/);
}

Is this what you're looking for?

这就是你要找的吗?

I hope it helps.

我希望它有帮助。

EDIT: I edited my example above so that there can only be one period, preceded by at least one digit and followed by at least one digit.

编辑:我编辑了上面的示例,以便只有一个句点,前面至少有一个数字,后面至少有一个数字。

#3


16  

The accepted solution is not complete, since you can enter multiple '.', for example 24....22..22. with some small modifications it will work as intended:

接受的解决方案不完整,因为您可以输入多个'。”,例如24 .... 22 . . 22。通过一些小的修改,它将按照预期工作:

<HTML><HEAD>
<script type="text/javascript">

 function isNumberKey(txt, evt) {

    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode == 46) {
        //Check if the text already contains the . character
        if (txt.value.indexOf('.') === -1) {
            return true;
        } else {
            return false;
        }
    } else {
        if (charCode > 31
             && (charCode < 48 || charCode > 57))
            return false;
    }
    return true;
}

</SCRIPT></HEAD><BODY>
<input type="text" onkeypress="return isNumberKey(this, event);" /> </BODY></HTML>

#4


9  

Here is one more solution which allows for decimal numbers and also limits the digits after decimal to 2 decimal places.

这里还有一个解决方案,允许十进制数,并将小数点后的数字限制为2位。

function isNumberKey(evt, element) {
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8))
    return false;
  else {
    var len = $(element).val().length;
    var index = $(element).val().indexOf('.');
    if (index > 0 && charCode == 46) {
      return false;
    }
    if (index > 0) {
      var CharAfterdot = (len + 1) - index;
      if (CharAfterdot > 3) {
        return false;
      }
    }

  }
  return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="rate" placeholder="Billing Rate" required onkeypress="return isNumberKey(event,this)">

#5


4  

Are you looking for something like this?

你在找这样的东西吗?

   <HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
   </BODY>
  </HTML>

#6


4  

Just need to apply this method in Jquery and you can validate your textbox to just accept number with a decimal only.

只需在Jquery中应用此方法,就可以验证文本框,只接受小数。

function IsFloatOnly(element) {    
var value = $(element).val(); 
var regExp ="^\\d+(\\.\\d+)?$";
return value.match(regExp); 
}

Please see working demo here

请参见这里的工作演示

#7


4  

All solutions presented here are using single key events. This is very error prone since input can be also given using copy'n'paste or drag'n'drop. Also some of the solutions restrict the usage of non-character keys like ctrl+c, Pos1 etc.

这里提供的所有解决方案都使用单个键事件。这很容易出错,因为输入也可以使用复制'n'paste或拖动'n'drop来提供。还有一些解决方案限制了非字符键的使用,如ctrl+c、Pos1等。

I suggest rather than checking every key press you check whether the result is valid in respect to your expectations.

我建议你不要检查每一个按键,而是检查结果是否符合你的期望。

var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = document.getElementById("test1").value;
function validateNumber(elem) {
  if (validNumber.test(elem.value)) {
    lastValid = elem.value;
  } else {
    elem.value = lastValid;
  }
}
<textarea id="test1" oninput="validateNumber(this);" ></textarea>

The oninput event is triggered just after something was changed in the text area and before being rendered.

oninput事件是在文本区域中发生了一些更改并呈现之前触发的。

You can extend the RegEx to whatever number format you want to accept. This is far more maintainable and extendible than checking for single key presses.

您可以将RegEx扩展到您想要接受的任何数字格式。与检查单个按键相比,这更易于维护和扩展。

#8


2  

For anyone stumbling here like I did, here is a jQuery 1.10.2 version I wrote which is working very well for me albeit resource intensive:

对于像我这样在这里遇到麻烦的人,我写了一个jQuery 1.10.2版本,虽然资源密集,但对我来说非常有用:

/***************************************************
* Only allow numbers and one decimal in text boxes
***************************************************/
$('body').on('keydown keyup keypress change blur focus paste', 'input[type="text"]', function(){
    var target = $(this);

    var prev_val = target.val();

    setTimeout(function(){
        var chars = target.val().split("");

        var decimal_exist = false;
        var remove_char = false;

        $.each(chars, function(key, value){
            switch(value){
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                case '.':
                    if(value === '.'){
                        if(decimal_exist === false){
                            decimal_exist = true;
                        }
                        else{
                            remove_char = true;
                            chars[''+key+''] = '';
                        }
                    }
                    break;
                default:
                    remove_char = true;
                    chars[''+key+''] = '';
                    break;
            }
        });

        if(prev_val != target.val() && remove_char === true){
            target.val(chars.join(''))
        }
    }, 0);
});

#9


2  

A small correction to @rebisco's brilliant answer to validate the decimal perfectly.

对@rebisco聪明的答案做一个小小的修正,以完美地验证小数。

function isNumberKey(evt) {
    debugger;
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode == 46 && evt.srcElement.value.split('.').length>1) {
        return false;
    }
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

#10


1  

inputelement.onchange= inputelement.onkeyup= function isnumber(e){
    e= window.event? e.srcElement: e.target;
    while(e.value && parseFloat(e.value)+''!= e.value){
            e.value= e.value.slice(0, -1);
    }
}

#11


1  

function integerwithdot(s, iid){
        var i;
        s = s.toString();
        for (i = 0; i < s.length; i++){
            var c;
            if (s.charAt(i) == ".") {
            } else {
                c = s.charAt(i);
            }
            if (isNaN(c)) {
                c = "";
                for(i=0;i<s.length-1;i++){
                    c += s.charAt(i);
                }
                document.getElementById(iid).value = c;
                return false;
            }
        }
        return true;
    }

#12


1  

here is script that cas help you :

以下是cas帮助您的脚本:

<script type="text/javascript">
// price text-box allow numeric and allow 2 decimal points only
function extractNumber(obj, decimalPlaces, allowNegative)
{
    var temp = obj.value;

    // avoid changing things if already formatted correctly
    var reg0Str = '[0-9]*';
    if (decimalPlaces > 0) {
        reg0Str += '\[\,\.]?[0-9]{0,' + decimalPlaces + '}';
    } else if (decimalPlaces < 0) {
        reg0Str += '\[\,\.]?[0-9]*';
    }
    reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
    reg0Str = reg0Str + '$';
    var reg0 = new RegExp(reg0Str);
    if (reg0.test(temp)) return true;

    // first replace all non numbers
    var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (decimalPlaces != 0 ? ',' : '') + (allowNegative ? '-' : '') + ']';
    var reg1 = new RegExp(reg1Str, 'g');
    temp = temp.replace(reg1, '');

    if (allowNegative) {
        // replace extra negative
        var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
        var reg2 = /-/g;
        temp = temp.replace(reg2, '');
        if (hasNegative) temp = '-' + temp;
    }

    if (decimalPlaces != 0) {
        var reg3 = /[\,\.]/g;
        var reg3Array = reg3.exec(temp);
        if (reg3Array != null) {
            // keep only first occurrence of .
            //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
            var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
            reg3Right = reg3Right.replace(reg3, '');
            reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
            temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
        }
    }

    obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
    var key;
    var isCtrl = false;
    var keychar;
    var reg;
    if(window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey
    }
    else if(e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    }

    if (isNaN(key)) return true;

    keychar = String.fromCharCode(key);

    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl)
    {
        return true;
    }

    reg = /\d/;
    var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
    var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
    var isFirstC = allowDecimal ? keychar == ',' && obj.value.indexOf(',') == -1 : false;
    return isFirstN || isFirstD || isFirstC || reg.test(keychar);
}
function blockInvalid(obj)
{
    var temp=obj.value;
    if(temp=="-")
    {
        temp="";
    }

    if (temp.indexOf(".")==temp.length-1 && temp.indexOf(".")!=-1)
    {
        temp=temp+"00";
    }
    if (temp.indexOf(".")==0)
    {
        temp="0"+temp;
    }
    if (temp.indexOf(".")==1 && temp.indexOf("-")==0)
    {
        temp=temp.replace("-","-0") ;
    }
    if (temp.indexOf(",")==temp.length-1 && temp.indexOf(",")!=-1)
    {
        temp=temp+"00";
    }
    if (temp.indexOf(",")==0)
    {
        temp="0"+temp;
    }
    if (temp.indexOf(",")==1 && temp.indexOf("-")==0)
    {
        temp=temp.replace("-","-0") ;
    }
    temp=temp.replace(",",".") ;
    obj.value=temp;
}
// end of price text-box allow numeric and allow 2 decimal points only
</script>

<input type="Text" id="id" value="" onblur="extractNumber(this,2,true);blockInvalid(this);" onkeyup="extractNumber(this,2,true);" onkeypress="return blockNonNumbers(this, event, true, true);">

#13


1  

Suppose your textbox field name is Income
Call this validate method when you need to validate your field:

假设您的文本框字段名是收入,当您需要验证字段时,请调用这个验证方法:

function validate() {
    var currency = document.getElementById("Income").value;
      var pattern = /^[1-9]\d*(?:\.\d{0,2})?$/ ;
    if (pattern.test(currency)) {
        alert("Currency is in valid format");
        return true;
    } 
        alert("Currency is not in valid format!Enter in 00.00 format");
        return false;
}

#14


1  

Extending the @rebisco's answer. this below code will allow only numbers and single '.'(period) in the text box.

延长@rebisco的回答。下面的代码将只允许文本框中的数字和单个'.'(句号)。

function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        } else {
            // If the number field already has . then don't allow to enter . again.
            if (evt.target.value.search(/\./) > -1 && charCode == 46) {
                return false;
            }
            return true;
        }
    }

#15


1  

Hope it will work for you.

希望它对你有用。

<input type="text" onkeypress="return chkNumeric(event)" />

<script>
    function chkNumeric(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            if (charCode == 46) { return true; }
            else { return false; }
        }
        return true;
    }
</script>

#16


1  

Better solution

更好的解决方案

var checkfloats = function(event){
    var charCode = (event.which) ? event.which : event.keyCode;
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    if(event.target.value.indexOf('.') >=0 && charCode == 46)
        return false;

    return true;
}

#17


0  

Starting from @rebisco answer :

从@rebisco开始回答:

function count_appearance(mainStr, searchFor) {
    return (mainStr.split(searchFor).length - 1);
}
function isNumberKey(evt)
{
    $return = true;
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31
            && (charCode < 48 || charCode > 57))
        $return = false;
    $val = $(evt.originalTarget).val();
    if (charCode == 46) {
        if (count_appearance($val, '.') > 0) {
            $return = false;
        }
        if ($val.length == 0) {
            $return = false;
        }
    }
    return $return;
}

Allows only this format : 123123123[.121213]

只允许这种格式:123123123[.121213]

Demo here demo

演示演示

#18


0  

Following code worked for me

下面的代码对我有用

The input box with "onkeypress" event as follows

带有“onkeypress”事件的输入框,如下所示

<input type="text" onkeypress="return isNumberKey(this,event);" />

The function "isNumberKey" is as follows

函数“isNumberKey”如下所示

function isNumberKey(txt, evt) {
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode == 46) {
    //Check if the text already contains the . character
    if (txt.value.indexOf('.') === -1) {
        return true;
    } else {
        return false;
    }
  } else {
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
  }
  return true;
}

#19


0  

I observed that for all the answers provided here, the things are not working if we select some portion of the text in textbox and try to overwrite that part. So I modified the function which is as below:

我注意到,对于这里提供的所有答案,如果我们在文本框中选择文本的某些部分并试图覆盖该部分,那么事情就无法进行。所以我对函数做了如下修改:

    <HTML>
  <HEAD>
    <SCRIPT language=Javascript>
       <!--
       function isNumberKey(evt)
       {
         var charCode = (evt.which) ? evt.which : event.keyCode;

if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
{
        return false;
}
 if (charCode == 46 && evt.srcElement.value.split('.').length>1 )
    {

        return false;

    } 

 if(evt.srcElement.selectionStart<evt.srcElement.selectionEnd)
    {
          return true;
    }

  if(evt.srcElement.value.split('.').length>1 && evt.srcElement.value.split('.')[1].length==2)
  {

     return false;
  }


    return true;
       }


       //-->
    </SCRIPT>
  </HEAD>
  <BODY>
    <INPUT id="txtChar" onkeypress="return isNumberKey(event)" 
           type="text" name="txtChar">
  </BODY>
</HTML>

#20


0  

For Decimal numbers and also allowing Negatives numbers with 2 places for decimals after the point... I modified the function to:

对于十进制数,也允许负数,小数点后两位……我将函数修改为:

<input type="text" id="txtSample" onkeypress="return isNumberKey(event,this)"/>



function isNumberKey(evt, element){

        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8 || charCode == 45))
            return false;
        else {
            var len = $(element).val().length;

            // Validation Point
            var index = $(element).val().indexOf('.');
            if ((index > 0 && charCode == 46) || len == 0 && charCode == 46) {
                return false;
            }
            if (index > 0) {
                var CharAfterdot = (len + 1) - index;
                if (CharAfterdot > 3) {
                    return false;
                }
            }

            // Validating Negative sign
            index = $(element).val().indexOf('-');
            if ((index > 0 && charCode == 45) || (len > 0 && charCode == 45)) {
                return false;
            }
        }
        return true;
    }

#21


0  

alternative way to restrict input to a text-box so that it accepts only numbers and the decimal point is to use javascript inside the html input. This works for me:

将输入限制为文本框的另一种方法是在html输入中使用javascript,以便文本框只接受数字和小数点。这工作对我来说:

<input type="text" class="form-control" id="price" name="price" placeholder="Price" 
vrequired onkeyup="this.value=this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')">

--Accepts--

——接受

9

9

9.99

9.99

--Do not accept--

——不接受

9.99.99

9.99.99

ABC

美国广播公司

#22


0  

function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : evt.keyCode;

    if(charCode==8 || charCode==13|| charCode==99|| charCode==118 || charCode==46)
    {    
        return true;  
    }

    if (charCode > 31 && (charCode < 48 || charCode > 57))
    {   
        return false; 
    }
    return true;
}

It will allow only numeric and will let you put "." for decimal.

它将只允许数字,并允许您输入“。”作为十进制。

#23


0  

<script type="text/javascript">

    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

        return true;
    }

</script>

@Html.EditorFor(model => model.Orderids, new { id = "Orderids", Onkeypress=isNumberKey(event)})

This works fine.

这是很好。

#24


0  

Best and working solution with Pure-Javascript sample Live demo : https://jsfiddle.net/manoj2010/ygkpa89o/

纯javascript示例实时演示的最佳工作解决方案:https://jsfiddle.net/manoj2010/ygkpa89o/

<script>
function removeCommas(nStr) {
    if (nStr == null || nStr == "")
        return ""; 
    return nStr.toString().replace(/,/g, "");
}

function NumbersOnly(myfield, e, dec,neg)
{        
    if (isNaN(removeCommas(myfield.value)) && myfield.value != "-") {
        return false;
    }
    var allowNegativeNumber = neg || false;
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);
    var srcEl = e.srcElement ? e.srcElement : e.target;    
    // control keys
    if ((key == null) || (key == 0) || (key == 8) ||
                (key == 9) || (key == 13) || (key == 27))
        return true;

    // numbers
    else if ((("0123456789").indexOf(keychar) > -1))
        return true;

    // decimal point jump
    else if (dec && (keychar == ".")) {
        //myfield.form.elements[dec].focus();
        return srcEl.value.indexOf(".") == -1;        
    }

    //allow negative numbers
    else if (allowNegativeNumber && (keychar == "-")) {    
        return (srcEl.value.length == 0 || srcEl.value == "0.00")
    }
    else
        return false;
}
</script>
<input name="txtDiscountSum" type="text" onKeyPress="return NumbersOnly(this, event,true)" /> 

#25


0  

Working on the issue myself, and that's what I've got so far. This more or less works, but it's impossible to add minus afterwards due to the new value check. Also doesn't allow comma as a thousand separator, only decimal.

我自己也在研究这个问题,这就是我到目前为止的成果。这或多或少是可行的,但是由于新的值检查,以后不可能添加负号。也不允许逗号作为千位分隔符,只允许十进制。

It's not perfect, but might give some ideas.

它并不完美,但可能会给你一些建议。

app.directive('isNumber', function () {
            return function (scope, elem, attrs) {
                elem.bind('keypress', function (evt) {
                    var keyCode = (evt.which) ? evt.which : event.keyCode;
                    var testValue = (elem[0].value + String.fromCharCode(keyCode) + "0").replace(/ /g, ""); //check ignores spaces
                    var regex = /^\-?\d+((\.|\,)\d+)?$/;                        
                    var allowedChars = [8,9,13,27,32,37,39,44,45, 46] //control keys and separators             

                   //allows numbers, separators and controll keys and rejects others
                    if ((keyCode > 47 && keyCode < 58) || allowedChars.indexOf(keyCode) >= 0) {             
                        //test the string with regex, decline if doesn't fit
                        if (elem[0].value != "" && !regex.test(testValue)) {
                            event.preventDefault();
                            return false;
                        }
                        return true;
                    }
                    event.preventDefault();
                    return false;
                });
            };
        });

Allows:

允许:

11 11 .245 (in controller formatted on blur to 1111.245)

11.245(在模糊到1111.245的控制器中)

11,44

11日,44

-123.123

-123.123

-1 014

1 014

0123 (formatted on blur to 123)

0123(格式化为模糊到123)

doesn't allow:

不允许:

!@#$/*

! @ # $ / *

abc

美国广播公司

11.11.1

11.11.1

11,11.1

11日,11.1

.42

#26


0  

<input type="text" onkeypress="return isNumberKey(event,this)">

<script>
   function isNumberKey(evt, obj) {

            var charCode = (evt.which) ? evt.which : event.keyCode
            var value = obj.value;
            var dotcontains = value.indexOf(".") != -1;
            if (dotcontains)
                if (charCode == 46) return false;
            if (charCode == 46) return true;
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
            return true;
        }


</script>

#27


0  

If you want it for float values,

如果你想要浮点数,

Here is the function I am using

这是我使用的函数

<HTML>

<HEAD>
  <SCRIPT language=Javascript>
    <!--
    function check(e, value) {
      //Check Charater
      var unicode = e.charCode ? e.charCode : e.keyCode;
      if (value.indexOf(".") != -1)
        if (unicode == 46) return false;
      if (unicode != 8)
        if ((unicode < 48 || unicode > 57) && unicode != 46) return false;
    }
    //-->
  </SCRIPT>
</HEAD>

<BODY>
  <INPUT id="txtChar" onkeypress="return check(event,value)" type="text" name="txtChar">
</BODY>

</HTML>

#28


0  

I know that this question is very old but still we often get such requirements. There are many examples however many seems to be too verbose or complex for a simple implimentation.

我知道这个问题很老了,但我们还是经常得到这样的要求。有许多例子,但许多似乎过于冗长或复杂,对于一个简单的强迫。

See this https://jsfiddle.net/vibs2006/rn0fvxuk/ and improve it (if you can). It works on IE, Firefox, Chrome and Edge Browser.

查看这个https://jsfiddle.net/vibs2006/rn0fvxuk/并改进它(如果可以的话)。它适用于IE、火狐、Chrome和Edge浏览器。

Here is the working code.

这是工作代码。

        
        function IsNumeric(e) {
        var IsValidationSuccessful = false;
        console.log(e.target.value);
        document.getElementById("info").innerHTML = "You just typed ''" + e.key + "''";
        //console.log("e.Key Value = "+e.key);
        switch (e.key)
         {         
             case "1":
             case "2":
             case "3":
             case "4":
             case "5":
             case "6":
             case "7":
             case "8":
             case "9":
             case "0":
             case "Backspace":             
                 IsValidationSuccessful = true;
                 break;
                 
						 case "Decimal":  //Numpad Decimal in Edge Browser
             case ".":        //Numpad Decimal in Chrome and Firefox                      
             case "Del": 			// Internet Explorer 11 and less Numpad Decimal 
                 if (e.target.value.indexOf(".") >= 1) //Checking if already Decimal exists
                 {
                     IsValidationSuccessful = false;
                 }
                 else
                 {
                     IsValidationSuccessful = true;
                 }
                 break;

             default:
                 IsValidationSuccessful = false;
         }
         //debugger;
         if(IsValidationSuccessful == false){
         
         document.getElementById("error").style = "display:Block";
         }else{
         document.getElementById("error").style = "display:none";
         }
         
         return IsValidationSuccessful;
        }
Numeric Value: <input type="number" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" /><br />
    <span id="error" style="color: Red; display: none">* Input digits (0 - 9) and Decimals Only</span><br />
    <div id="info"></div>

#29


-1  

<input type="text" class="number_only" />    
<script>
$(document).ready(function() {
    $('.number_only').keypress(function (event) {
        return isNumber(event, this)
    });        
});

function isNumber(evt, element) {
    var charCode = (evt.which) ? evt.which : event.keyCode

    if ((charCode != 45 || $(element).val().indexOf('-') != -1) && (charCode != 46 || $(element).val().indexOf('.') != -1) && ((charCode < 48 && charCode != 8) || charCode > 57)){
        return false;
    }
    else {
        return true;
    }
} 
</script>

http://www.encodedna.com/2013/05/enter-only-numbers-using-jquery.htm

http://www.encodedna.com/2013/05/enter-only-numbers-using-jquery.htm

#30


-1  

document.getElementById('value').addEventListener('keydown', function(e) {
    var key   = e.keyCode ? e.keyCode : e.which;

/*lenght of value to use with index to know how many numbers after.*/

    var len = $('#value').val().length;
    var index = $('#value').val().indexOf('.');
    if (!( [8, 9, 13, 27, 46, 110, 190].indexOf(key) !== -1 ||
                    (key == 65 && ( e.ctrlKey || e.metaKey  ) ) ||
                    (key >= 35 && key <= 40) ||
                    (key >= 48 && key <= 57 && !(e.shiftKey || e.altKey)) ||
                    (key >= 96 && key <= 105)
            )){
        e.preventDefault();
    }

/*if theres a . count how many and if reachs 2 digits after . it blocks*/ 

    if (index > 0) {
        var CharAfterdot = (len + 1) - index;
        if (CharAfterdot > 3) {

/*permits the backsapce to remove :D could be improved*/

            if (!(key == 8))
            {
                e.preventDefault();
            }

/*blocks if you try to add a new . */

        }else if ( key == 110) {
            e.preventDefault();
        }

/*if you try to add a . and theres no digit yet it adds a 0.*/

    } else if( key == 110&& len==0){
        e.preventDefault();
        $('#value').val('0.');
    }
});

#1


137  

<HTML>
  <HEAD>
    <SCRIPT language=Javascript>
       <!--
       function isNumberKey(evt)
       {
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;

          return true;
       }
       //-->
    </SCRIPT>
  </HEAD>
  <BODY>
    <INPUT id="txtChar" onkeypress="return isNumberKey(event)" 
           type="text" name="txtChar">
  </BODY>
</HTML>

This really works!

这确实有效!

#2


24  

form.onsubmit = function(){
    return textarea.value.match(/^\d+(\.\d+)?$/);
}

Is this what you're looking for?

这就是你要找的吗?

I hope it helps.

我希望它有帮助。

EDIT: I edited my example above so that there can only be one period, preceded by at least one digit and followed by at least one digit.

编辑:我编辑了上面的示例,以便只有一个句点,前面至少有一个数字,后面至少有一个数字。

#3


16  

The accepted solution is not complete, since you can enter multiple '.', for example 24....22..22. with some small modifications it will work as intended:

接受的解决方案不完整,因为您可以输入多个'。”,例如24 .... 22 . . 22。通过一些小的修改,它将按照预期工作:

<HTML><HEAD>
<script type="text/javascript">

 function isNumberKey(txt, evt) {

    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode == 46) {
        //Check if the text already contains the . character
        if (txt.value.indexOf('.') === -1) {
            return true;
        } else {
            return false;
        }
    } else {
        if (charCode > 31
             && (charCode < 48 || charCode > 57))
            return false;
    }
    return true;
}

</SCRIPT></HEAD><BODY>
<input type="text" onkeypress="return isNumberKey(this, event);" /> </BODY></HTML>

#4


9  

Here is one more solution which allows for decimal numbers and also limits the digits after decimal to 2 decimal places.

这里还有一个解决方案,允许十进制数,并将小数点后的数字限制为2位。

function isNumberKey(evt, element) {
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8))
    return false;
  else {
    var len = $(element).val().length;
    var index = $(element).val().indexOf('.');
    if (index > 0 && charCode == 46) {
      return false;
    }
    if (index > 0) {
      var CharAfterdot = (len + 1) - index;
      if (CharAfterdot > 3) {
        return false;
      }
    }

  }
  return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="rate" placeholder="Billing Rate" required onkeypress="return isNumberKey(event,this)">

#5


4  

Are you looking for something like this?

你在找这样的东西吗?

   <HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
   </BODY>
  </HTML>

#6


4  

Just need to apply this method in Jquery and you can validate your textbox to just accept number with a decimal only.

只需在Jquery中应用此方法,就可以验证文本框,只接受小数。

function IsFloatOnly(element) {    
var value = $(element).val(); 
var regExp ="^\\d+(\\.\\d+)?$";
return value.match(regExp); 
}

Please see working demo here

请参见这里的工作演示

#7


4  

All solutions presented here are using single key events. This is very error prone since input can be also given using copy'n'paste or drag'n'drop. Also some of the solutions restrict the usage of non-character keys like ctrl+c, Pos1 etc.

这里提供的所有解决方案都使用单个键事件。这很容易出错,因为输入也可以使用复制'n'paste或拖动'n'drop来提供。还有一些解决方案限制了非字符键的使用,如ctrl+c、Pos1等。

I suggest rather than checking every key press you check whether the result is valid in respect to your expectations.

我建议你不要检查每一个按键,而是检查结果是否符合你的期望。

var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = document.getElementById("test1").value;
function validateNumber(elem) {
  if (validNumber.test(elem.value)) {
    lastValid = elem.value;
  } else {
    elem.value = lastValid;
  }
}
<textarea id="test1" oninput="validateNumber(this);" ></textarea>

The oninput event is triggered just after something was changed in the text area and before being rendered.

oninput事件是在文本区域中发生了一些更改并呈现之前触发的。

You can extend the RegEx to whatever number format you want to accept. This is far more maintainable and extendible than checking for single key presses.

您可以将RegEx扩展到您想要接受的任何数字格式。与检查单个按键相比,这更易于维护和扩展。

#8


2  

For anyone stumbling here like I did, here is a jQuery 1.10.2 version I wrote which is working very well for me albeit resource intensive:

对于像我这样在这里遇到麻烦的人,我写了一个jQuery 1.10.2版本,虽然资源密集,但对我来说非常有用:

/***************************************************
* Only allow numbers and one decimal in text boxes
***************************************************/
$('body').on('keydown keyup keypress change blur focus paste', 'input[type="text"]', function(){
    var target = $(this);

    var prev_val = target.val();

    setTimeout(function(){
        var chars = target.val().split("");

        var decimal_exist = false;
        var remove_char = false;

        $.each(chars, function(key, value){
            switch(value){
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                case '.':
                    if(value === '.'){
                        if(decimal_exist === false){
                            decimal_exist = true;
                        }
                        else{
                            remove_char = true;
                            chars[''+key+''] = '';
                        }
                    }
                    break;
                default:
                    remove_char = true;
                    chars[''+key+''] = '';
                    break;
            }
        });

        if(prev_val != target.val() && remove_char === true){
            target.val(chars.join(''))
        }
    }, 0);
});

#9


2  

A small correction to @rebisco's brilliant answer to validate the decimal perfectly.

对@rebisco聪明的答案做一个小小的修正,以完美地验证小数。

function isNumberKey(evt) {
    debugger;
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode == 46 && evt.srcElement.value.split('.').length>1) {
        return false;
    }
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

#10


1  

inputelement.onchange= inputelement.onkeyup= function isnumber(e){
    e= window.event? e.srcElement: e.target;
    while(e.value && parseFloat(e.value)+''!= e.value){
            e.value= e.value.slice(0, -1);
    }
}

#11


1  

function integerwithdot(s, iid){
        var i;
        s = s.toString();
        for (i = 0; i < s.length; i++){
            var c;
            if (s.charAt(i) == ".") {
            } else {
                c = s.charAt(i);
            }
            if (isNaN(c)) {
                c = "";
                for(i=0;i<s.length-1;i++){
                    c += s.charAt(i);
                }
                document.getElementById(iid).value = c;
                return false;
            }
        }
        return true;
    }

#12


1  

here is script that cas help you :

以下是cas帮助您的脚本:

<script type="text/javascript">
// price text-box allow numeric and allow 2 decimal points only
function extractNumber(obj, decimalPlaces, allowNegative)
{
    var temp = obj.value;

    // avoid changing things if already formatted correctly
    var reg0Str = '[0-9]*';
    if (decimalPlaces > 0) {
        reg0Str += '\[\,\.]?[0-9]{0,' + decimalPlaces + '}';
    } else if (decimalPlaces < 0) {
        reg0Str += '\[\,\.]?[0-9]*';
    }
    reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
    reg0Str = reg0Str + '$';
    var reg0 = new RegExp(reg0Str);
    if (reg0.test(temp)) return true;

    // first replace all non numbers
    var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (decimalPlaces != 0 ? ',' : '') + (allowNegative ? '-' : '') + ']';
    var reg1 = new RegExp(reg1Str, 'g');
    temp = temp.replace(reg1, '');

    if (allowNegative) {
        // replace extra negative
        var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
        var reg2 = /-/g;
        temp = temp.replace(reg2, '');
        if (hasNegative) temp = '-' + temp;
    }

    if (decimalPlaces != 0) {
        var reg3 = /[\,\.]/g;
        var reg3Array = reg3.exec(temp);
        if (reg3Array != null) {
            // keep only first occurrence of .
            //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
            var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
            reg3Right = reg3Right.replace(reg3, '');
            reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
            temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
        }
    }

    obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
    var key;
    var isCtrl = false;
    var keychar;
    var reg;
    if(window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey
    }
    else if(e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    }

    if (isNaN(key)) return true;

    keychar = String.fromCharCode(key);

    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl)
    {
        return true;
    }

    reg = /\d/;
    var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
    var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
    var isFirstC = allowDecimal ? keychar == ',' && obj.value.indexOf(',') == -1 : false;
    return isFirstN || isFirstD || isFirstC || reg.test(keychar);
}
function blockInvalid(obj)
{
    var temp=obj.value;
    if(temp=="-")
    {
        temp="";
    }

    if (temp.indexOf(".")==temp.length-1 && temp.indexOf(".")!=-1)
    {
        temp=temp+"00";
    }
    if (temp.indexOf(".")==0)
    {
        temp="0"+temp;
    }
    if (temp.indexOf(".")==1 && temp.indexOf("-")==0)
    {
        temp=temp.replace("-","-0") ;
    }
    if (temp.indexOf(",")==temp.length-1 && temp.indexOf(",")!=-1)
    {
        temp=temp+"00";
    }
    if (temp.indexOf(",")==0)
    {
        temp="0"+temp;
    }
    if (temp.indexOf(",")==1 && temp.indexOf("-")==0)
    {
        temp=temp.replace("-","-0") ;
    }
    temp=temp.replace(",",".") ;
    obj.value=temp;
}
// end of price text-box allow numeric and allow 2 decimal points only
</script>

<input type="Text" id="id" value="" onblur="extractNumber(this,2,true);blockInvalid(this);" onkeyup="extractNumber(this,2,true);" onkeypress="return blockNonNumbers(this, event, true, true);">

#13


1  

Suppose your textbox field name is Income
Call this validate method when you need to validate your field:

假设您的文本框字段名是收入,当您需要验证字段时,请调用这个验证方法:

function validate() {
    var currency = document.getElementById("Income").value;
      var pattern = /^[1-9]\d*(?:\.\d{0,2})?$/ ;
    if (pattern.test(currency)) {
        alert("Currency is in valid format");
        return true;
    } 
        alert("Currency is not in valid format!Enter in 00.00 format");
        return false;
}

#14


1  

Extending the @rebisco's answer. this below code will allow only numbers and single '.'(period) in the text box.

延长@rebisco的回答。下面的代码将只允许文本框中的数字和单个'.'(句号)。

function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        } else {
            // If the number field already has . then don't allow to enter . again.
            if (evt.target.value.search(/\./) > -1 && charCode == 46) {
                return false;
            }
            return true;
        }
    }

#15


1  

Hope it will work for you.

希望它对你有用。

<input type="text" onkeypress="return chkNumeric(event)" />

<script>
    function chkNumeric(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            if (charCode == 46) { return true; }
            else { return false; }
        }
        return true;
    }
</script>

#16


1  

Better solution

更好的解决方案

var checkfloats = function(event){
    var charCode = (event.which) ? event.which : event.keyCode;
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    if(event.target.value.indexOf('.') >=0 && charCode == 46)
        return false;

    return true;
}

#17


0  

Starting from @rebisco answer :

从@rebisco开始回答:

function count_appearance(mainStr, searchFor) {
    return (mainStr.split(searchFor).length - 1);
}
function isNumberKey(evt)
{
    $return = true;
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31
            && (charCode < 48 || charCode > 57))
        $return = false;
    $val = $(evt.originalTarget).val();
    if (charCode == 46) {
        if (count_appearance($val, '.') > 0) {
            $return = false;
        }
        if ($val.length == 0) {
            $return = false;
        }
    }
    return $return;
}

Allows only this format : 123123123[.121213]

只允许这种格式:123123123[.121213]

Demo here demo

演示演示

#18


0  

Following code worked for me

下面的代码对我有用

The input box with "onkeypress" event as follows

带有“onkeypress”事件的输入框,如下所示

<input type="text" onkeypress="return isNumberKey(this,event);" />

The function "isNumberKey" is as follows

函数“isNumberKey”如下所示

function isNumberKey(txt, evt) {
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode == 46) {
    //Check if the text already contains the . character
    if (txt.value.indexOf('.') === -1) {
        return true;
    } else {
        return false;
    }
  } else {
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
  }
  return true;
}

#19


0  

I observed that for all the answers provided here, the things are not working if we select some portion of the text in textbox and try to overwrite that part. So I modified the function which is as below:

我注意到,对于这里提供的所有答案,如果我们在文本框中选择文本的某些部分并试图覆盖该部分,那么事情就无法进行。所以我对函数做了如下修改:

    <HTML>
  <HEAD>
    <SCRIPT language=Javascript>
       <!--
       function isNumberKey(evt)
       {
         var charCode = (evt.which) ? evt.which : event.keyCode;

if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
{
        return false;
}
 if (charCode == 46 && evt.srcElement.value.split('.').length>1 )
    {

        return false;

    } 

 if(evt.srcElement.selectionStart<evt.srcElement.selectionEnd)
    {
          return true;
    }

  if(evt.srcElement.value.split('.').length>1 && evt.srcElement.value.split('.')[1].length==2)
  {

     return false;
  }


    return true;
       }


       //-->
    </SCRIPT>
  </HEAD>
  <BODY>
    <INPUT id="txtChar" onkeypress="return isNumberKey(event)" 
           type="text" name="txtChar">
  </BODY>
</HTML>

#20


0  

For Decimal numbers and also allowing Negatives numbers with 2 places for decimals after the point... I modified the function to:

对于十进制数,也允许负数,小数点后两位……我将函数修改为:

<input type="text" id="txtSample" onkeypress="return isNumberKey(event,this)"/>



function isNumberKey(evt, element){

        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8 || charCode == 45))
            return false;
        else {
            var len = $(element).val().length;

            // Validation Point
            var index = $(element).val().indexOf('.');
            if ((index > 0 && charCode == 46) || len == 0 && charCode == 46) {
                return false;
            }
            if (index > 0) {
                var CharAfterdot = (len + 1) - index;
                if (CharAfterdot > 3) {
                    return false;
                }
            }

            // Validating Negative sign
            index = $(element).val().indexOf('-');
            if ((index > 0 && charCode == 45) || (len > 0 && charCode == 45)) {
                return false;
            }
        }
        return true;
    }

#21


0  

alternative way to restrict input to a text-box so that it accepts only numbers and the decimal point is to use javascript inside the html input. This works for me:

将输入限制为文本框的另一种方法是在html输入中使用javascript,以便文本框只接受数字和小数点。这工作对我来说:

<input type="text" class="form-control" id="price" name="price" placeholder="Price" 
vrequired onkeyup="this.value=this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')">

--Accepts--

——接受

9

9

9.99

9.99

--Do not accept--

——不接受

9.99.99

9.99.99

ABC

美国广播公司

#22


0  

function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : evt.keyCode;

    if(charCode==8 || charCode==13|| charCode==99|| charCode==118 || charCode==46)
    {    
        return true;  
    }

    if (charCode > 31 && (charCode < 48 || charCode > 57))
    {   
        return false; 
    }
    return true;
}

It will allow only numeric and will let you put "." for decimal.

它将只允许数字,并允许您输入“。”作为十进制。

#23


0  

<script type="text/javascript">

    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

        return true;
    }

</script>

@Html.EditorFor(model => model.Orderids, new { id = "Orderids", Onkeypress=isNumberKey(event)})

This works fine.

这是很好。

#24


0  

Best and working solution with Pure-Javascript sample Live demo : https://jsfiddle.net/manoj2010/ygkpa89o/

纯javascript示例实时演示的最佳工作解决方案:https://jsfiddle.net/manoj2010/ygkpa89o/

<script>
function removeCommas(nStr) {
    if (nStr == null || nStr == "")
        return ""; 
    return nStr.toString().replace(/,/g, "");
}

function NumbersOnly(myfield, e, dec,neg)
{        
    if (isNaN(removeCommas(myfield.value)) && myfield.value != "-") {
        return false;
    }
    var allowNegativeNumber = neg || false;
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);
    var srcEl = e.srcElement ? e.srcElement : e.target;    
    // control keys
    if ((key == null) || (key == 0) || (key == 8) ||
                (key == 9) || (key == 13) || (key == 27))
        return true;

    // numbers
    else if ((("0123456789").indexOf(keychar) > -1))
        return true;

    // decimal point jump
    else if (dec && (keychar == ".")) {
        //myfield.form.elements[dec].focus();
        return srcEl.value.indexOf(".") == -1;        
    }

    //allow negative numbers
    else if (allowNegativeNumber && (keychar == "-")) {    
        return (srcEl.value.length == 0 || srcEl.value == "0.00")
    }
    else
        return false;
}
</script>
<input name="txtDiscountSum" type="text" onKeyPress="return NumbersOnly(this, event,true)" /> 

#25


0  

Working on the issue myself, and that's what I've got so far. This more or less works, but it's impossible to add minus afterwards due to the new value check. Also doesn't allow comma as a thousand separator, only decimal.

我自己也在研究这个问题,这就是我到目前为止的成果。这或多或少是可行的,但是由于新的值检查,以后不可能添加负号。也不允许逗号作为千位分隔符,只允许十进制。

It's not perfect, but might give some ideas.

它并不完美,但可能会给你一些建议。

app.directive('isNumber', function () {
            return function (scope, elem, attrs) {
                elem.bind('keypress', function (evt) {
                    var keyCode = (evt.which) ? evt.which : event.keyCode;
                    var testValue = (elem[0].value + String.fromCharCode(keyCode) + "0").replace(/ /g, ""); //check ignores spaces
                    var regex = /^\-?\d+((\.|\,)\d+)?$/;                        
                    var allowedChars = [8,9,13,27,32,37,39,44,45, 46] //control keys and separators             

                   //allows numbers, separators and controll keys and rejects others
                    if ((keyCode > 47 && keyCode < 58) || allowedChars.indexOf(keyCode) >= 0) {             
                        //test the string with regex, decline if doesn't fit
                        if (elem[0].value != "" && !regex.test(testValue)) {
                            event.preventDefault();
                            return false;
                        }
                        return true;
                    }
                    event.preventDefault();
                    return false;
                });
            };
        });

Allows:

允许:

11 11 .245 (in controller formatted on blur to 1111.245)

11.245(在模糊到1111.245的控制器中)

11,44

11日,44

-123.123

-123.123

-1 014

1 014

0123 (formatted on blur to 123)

0123(格式化为模糊到123)

doesn't allow:

不允许:

!@#$/*

! @ # $ / *

abc

美国广播公司

11.11.1

11.11.1

11,11.1

11日,11.1

.42

#26


0  

<input type="text" onkeypress="return isNumberKey(event,this)">

<script>
   function isNumberKey(evt, obj) {

            var charCode = (evt.which) ? evt.which : event.keyCode
            var value = obj.value;
            var dotcontains = value.indexOf(".") != -1;
            if (dotcontains)
                if (charCode == 46) return false;
            if (charCode == 46) return true;
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
            return true;
        }


</script>

#27


0  

If you want it for float values,

如果你想要浮点数,

Here is the function I am using

这是我使用的函数

<HTML>

<HEAD>
  <SCRIPT language=Javascript>
    <!--
    function check(e, value) {
      //Check Charater
      var unicode = e.charCode ? e.charCode : e.keyCode;
      if (value.indexOf(".") != -1)
        if (unicode == 46) return false;
      if (unicode != 8)
        if ((unicode < 48 || unicode > 57) && unicode != 46) return false;
    }
    //-->
  </SCRIPT>
</HEAD>

<BODY>
  <INPUT id="txtChar" onkeypress="return check(event,value)" type="text" name="txtChar">
</BODY>

</HTML>

#28


0  

I know that this question is very old but still we often get such requirements. There are many examples however many seems to be too verbose or complex for a simple implimentation.

我知道这个问题很老了,但我们还是经常得到这样的要求。有许多例子,但许多似乎过于冗长或复杂,对于一个简单的强迫。

See this https://jsfiddle.net/vibs2006/rn0fvxuk/ and improve it (if you can). It works on IE, Firefox, Chrome and Edge Browser.

查看这个https://jsfiddle.net/vibs2006/rn0fvxuk/并改进它(如果可以的话)。它适用于IE、火狐、Chrome和Edge浏览器。

Here is the working code.

这是工作代码。

        
        function IsNumeric(e) {
        var IsValidationSuccessful = false;
        console.log(e.target.value);
        document.getElementById("info").innerHTML = "You just typed ''" + e.key + "''";
        //console.log("e.Key Value = "+e.key);
        switch (e.key)
         {         
             case "1":
             case "2":
             case "3":
             case "4":
             case "5":
             case "6":
             case "7":
             case "8":
             case "9":
             case "0":
             case "Backspace":             
                 IsValidationSuccessful = true;
                 break;
                 
						 case "Decimal":  //Numpad Decimal in Edge Browser
             case ".":        //Numpad Decimal in Chrome and Firefox                      
             case "Del": 			// Internet Explorer 11 and less Numpad Decimal 
                 if (e.target.value.indexOf(".") >= 1) //Checking if already Decimal exists
                 {
                     IsValidationSuccessful = false;
                 }
                 else
                 {
                     IsValidationSuccessful = true;
                 }
                 break;

             default:
                 IsValidationSuccessful = false;
         }
         //debugger;
         if(IsValidationSuccessful == false){
         
         document.getElementById("error").style = "display:Block";
         }else{
         document.getElementById("error").style = "display:none";
         }
         
         return IsValidationSuccessful;
        }
Numeric Value: <input type="number" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" /><br />
    <span id="error" style="color: Red; display: none">* Input digits (0 - 9) and Decimals Only</span><br />
    <div id="info"></div>

#29


-1  

<input type="text" class="number_only" />    
<script>
$(document).ready(function() {
    $('.number_only').keypress(function (event) {
        return isNumber(event, this)
    });        
});

function isNumber(evt, element) {
    var charCode = (evt.which) ? evt.which : event.keyCode

    if ((charCode != 45 || $(element).val().indexOf('-') != -1) && (charCode != 46 || $(element).val().indexOf('.') != -1) && ((charCode < 48 && charCode != 8) || charCode > 57)){
        return false;
    }
    else {
        return true;
    }
} 
</script>

http://www.encodedna.com/2013/05/enter-only-numbers-using-jquery.htm

http://www.encodedna.com/2013/05/enter-only-numbers-using-jquery.htm

#30


-1  

document.getElementById('value').addEventListener('keydown', function(e) {
    var key   = e.keyCode ? e.keyCode : e.which;

/*lenght of value to use with index to know how many numbers after.*/

    var len = $('#value').val().length;
    var index = $('#value').val().indexOf('.');
    if (!( [8, 9, 13, 27, 46, 110, 190].indexOf(key) !== -1 ||
                    (key == 65 && ( e.ctrlKey || e.metaKey  ) ) ||
                    (key >= 35 && key <= 40) ||
                    (key >= 48 && key <= 57 && !(e.shiftKey || e.altKey)) ||
                    (key >= 96 && key <= 105)
            )){
        e.preventDefault();
    }

/*if theres a . count how many and if reachs 2 digits after . it blocks*/ 

    if (index > 0) {
        var CharAfterdot = (len + 1) - index;
        if (CharAfterdot > 3) {

/*permits the backsapce to remove :D could be improved*/

            if (!(key == 8))
            {
                e.preventDefault();
            }

/*blocks if you try to add a new . */

        }else if ( key == 110) {
            e.preventDefault();
        }

/*if you try to add a . and theres no digit yet it adds a 0.*/

    } else if( key == 110&& len==0){
        e.preventDefault();
        $('#value').val('0.');
    }
});