只允许输入浮点数 [英] allowing input only for float number

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

问题描述

在输入仅允许使用jQuery库使用浮点数的输入时,我有些痛苦。我的代码无法阻止字符。当它成为首次输入时,有人可以指导我解决此问题吗?

I have pain-time when making input that only allows float number with jquery library. my code can't prevent chacacter "." when it's becoming first input, can anyone guide me to solve this problem?

$('.filterme').keypress(function(eve) {
   if (    ( eve.which != 46 || $(this).val().indexOf('.') != -1 ) 
        && ( eve.which <  48 || eve.which > 57 ) 
        || ( $(this).val().indexOf('.') == 0) 
      )
   {
       eve.preventDefault();
   }
});​


推荐答案

我过滤了第一个使用jQuery Caret插件进行位置输入。否则,一旦键入点,就已经很晚了无法检查它的放置位置。我尝试检查该点,然后删除该点,但它看起来不太好。

I filter the first position input with the jQuery Caret plugin. Otherwise, once the dot is typed, it's already late to check where it was placed. I tried checking for the dot, then deleting the dot, but it does not look nice.

jQuery caret插件:
http://examplet.buss.hk/js/jquery.caret.min.js

jQuery caret plugin: http://examplet.buss.hk/js/jquery.caret.min.js

我做了什么:

http://jsfiddle.net/FCWrE/422/

尝试一下:)

$('.filterme').keypress(function(eve) {
  if ((eve.which != 46 || $(this).val().indexOf('.') != -1) && (eve.which < 48 || eve.which > 57) || (eve.which == 46 && $(this).caret().start == 0)) {
    eve.preventDefault();
  }

  // this part is when left part of number is deleted and leaves a . in the leftmost position. For example, 33.25, then 33 is deleted
  $('.filterme').keyup(function(eve) {
    if ($(this).val().indexOf('.') == 0) {
      $(this).val($(this).val().substring(1));
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/caret/1.0.0/jquery.caret.min.js"></script>
<input type="text" class="filterme">

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

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