只允许数字,小数,负数 [英] Only allow numbers, decimals, negative

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

问题描述

我有此代码,仅允许在keypress()的输入字段中输入数字

I have this code that only permits numbers to be entered in an input field on keypress()

if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    return false;
}

我还如何允许小数和减键?

How can I also allow decimals, and minus keypress?

推荐答案

这是一个解决方案,但是我建议使用掩码插件,例如:

This is a solution, but I recommend to use mask plugin, for example: jQuery-Mask-Plugin

$("#id").keypress(function(e){
  if (e.which != 46 && e.which != 45 && e.which != 46 &&
      !(e.which >= 48 && e.which <= 57)) {
    return false;
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="id" />

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

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