只允许将数字放入输入文本框中 [英] Allow only numbers into a input text box

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

问题描述

我有一个数字输入文本框,我想允许用户进行编辑,但不希望允许用户输入除数字之外的任何其他文本。我希望他们只能使用数字输入框中的箭头。

 < input type =numbermin =0max =10step =0.5input id =ratingname =ratingclass =login-inputplaceholder =Rating 1-5:value =0> 


解决方案

您可以通过纯的JavaScript 。在你的脚本中创建这个函数并将它称为 onkeypress 事件处理程序。

  < script type =text / javascript> 
函数AllowNumbersOnly(e){
var code =(e.which)? e.which:e.keyCode; (代码> 31&&(code< 48 || code> 57)){
e.preventDefault();
}
}
< / script>

并像这样调用这个函数 onkeypress

 < input type =textid =OnlyNumbersonkeypress =return AllowNumbersOnly(event)/> 

工作 Demo。 然而,我会推荐使用jQuery编写JS的不显眼风格,因为我没有像污染 HTML

  $(function(){
$('#OnlyNumbers')。keydown(function(e){
return AllowNumbersOnly(e);
});
});

若要限制每个字符,您可以省略 if 条件和使用 preventDefault() 来禁用所有密钥。



另外,您也可以使用 return false 但是在这种情况下 preventDefault()更好,并且应该明智地选择 return false 。了解两者之间的差异是很好的。


I have a number input text box and I want to allow the user to edit but do not want to allow the user to enter any other text except numbers. I want them only to be able to use the arrows on the number input box.

 <input type = "number" min="0" max="10" step="0.5"  input id="rating"   name = "rating" class = "login-input" placeholder = "Rating 1-5:" value="0">

解决方案

You can achieve this by pure JavaScript. Create this function in your script and call it onkeypress event handler.

<script type="text/javascript">
  function AllowNumbersOnly(e) {
    var code = (e.which) ? e.which : e.keyCode;
    if (code > 31 && (code < 48 || code > 57)) {
      e.preventDefault();
    }
  }
</script>

and call this function onkeypress like this.

<input type="text" id="OnlyNumbers" onkeypress = "return AllowNumbersOnly(event)" />

Working Demo.

However i would recommend the unobtrusive style of writing JS using jQuery because i do not like to pollute HTML.

$(function(){
  $('#OnlyNumbers').keydown(function(e){
      return AllowNumbersOnly(e);
  });
});

To restrict every character you may omit the if condition and use preventDefault() to disable all keys.

Besides, you can also use return false instead but preventDefault() is better in this case and return false should have been chosen wisely. It is good to know the difference between both of them.

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

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