0

我不想在文本框中允许十进制值。我已经编写了代码,但只有在删除整个值然后重新插入它时它才有效。我的问题是当我尝试编辑现有值时,它采用十进制数字.. 这是 jsfiddle。这是供参考的代码:

HTML

<input id="Amt"  type="text" value="$78.00">

jQuery

 $(document).ready(function () {

    $("#Amt").keydown(function (e) {
        if ((!e.shiftKey && !e.ctrlKey && !e.altKey) && ((e.keyCode >= 48 && e.keyCode <= 57) ||
                (e.keyCode >= 96 && e.keyCode <= 105))) {
        }
        else if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 39 &&
                     e.keyCode != 9) {
            e.preventDefault();
        }
    });

   $("#Amt").keyup(function (e) {
        var value = $(this).val();
       var newValue = parseFloat(value).toFixed(2);
        if (!isNaN(newValue)) {
            $(this).val(newValue);
            $(this).caret(newValue.length - 3, newValue.length - 3);
        }
    });
});
4

3 回答 3

1

如果你想保持这种格式,你可以使用字符串方法去掉小数点并重新附加“.00”。

  $("#Amt").blur(function (e) {
    var value = this.value.replace(/\$/g,"");
    var dotPos = value.indexOf(".");
    var dollars = dotPos>-1?value.substring(0,dotPos):value;
    $(this).val(dollars+".00");
  });

  $("#Amt").blur();

http://jsfiddle.net/ZUj8M/14/

于 2013-01-08T16:44:38.270 回答
0

我会以一种完全不同的方式来处理它,只是首先防止小数到达那里。http://jsfiddle.net/ZUj8M/7/

$(document).ready(function () {

  var timer;
  $("#Amt").on("keydown paste input",function (e) {
    var el = this,
      origval = this.value;
    clearTimeout(timer);
    timer = setTimeout(function () {
      if (origval != el.value && /\./.test(el.value)) {
        el.value = origval;
        alert("Decimals are not allowed in this field.");
      }
    }, 0);
  });
  if (/\./.test($("#Amt").val())) {
    $("#Amt").val($("#Amt").val().replace(/\./g,""));
  }

});

或者,您可以直接删除小数,而不是撤消更改。

// el.value = origval;
// alert("Decimals are not allowed in this field.");
el.value = el.value.replace(/\./g,"");
于 2013-01-08T16:36:13.653 回答
0

为什么不将给定值解析为整数?

var newValue = parseInt(floatValue, 10);

然后允许用户插入一个点“。” 在 .blur()-event 上,您可以将浮点数解析为 int ...

$("#Amt").blur(function() {
    $this.val(parseInt(jQuery(this).val(), 10));
});
于 2013-01-08T16:57:10.660 回答