有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?


当前回答

希望我不是用一个丑陋的棍子在这里打死马,但我用这个为我的网站数量输入,它只允许从1到99的数字。

试一试: https://jsfiddle.net/83va5sb9/

      <input min="1" type="text" id="quantity" name="quantity" value="1"
      onKeyUp="numbersonly()">

      <script>
    function numbersonly() {
      var str = document.getElementById("quantity").value
      var newstr = ""
      for (i = 0; i < str.length; i++) {
        for (ii = 1; ii < 10; ii++) {
          if (str.charAt(i).indexOf(ii) > -1) {
            newstr += str.charAt(i)
          }
        }
      }
      if (newstr == "") {
        newstr = 1
      }
      if (parseInt(newstr) > 99) {
        newstr = 99
      }
      document.getElementById("quantity").value = newstr
    }

    </script>

其他回答

我用完了这个函数:

onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) return false;"

这在IE和Chrome中工作得很好,我不知道为什么它在firefox中也不工作得很好,这个功能在firefox中阻止了tab键。

对于tab键在firefox中工作很好,添加这个:

onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) if(event.keyCode != 9) return false;"

这是一个改进的函数:

function validateNumber(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();
  }
}
<input name="amount" type="text" value="Only number in here"/> 

<script>
    $('input[name=amount]').keyup(function(){
        $(this).val($(this).val().replace(/[^\d]/,''));
    });
</script>

jQuery的另一个简单方法:

$('.Numeric').bind('keydown',function(e){
    if (e.which < 48 || e.which > 57)
        return false;
    return true;
})

现在只需将每个输入类设置为Numeric,如下所示:

<input type="text" id="inp2" name="inp2" class='Numeric' />

//在JavaScript函数中(可以使用HTML或PHP)。

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

在您的表单输入:

<input type=text name=form_number size=20 maxlength=12 onkeypress='return isNumberKey(event)'>

输入max。(以上这些允许使用12位数字)