且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

只允许输入浮点数

更新时间:2023-02-21 11:47:01

我过滤了第一个使用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">