ATM style decimal places

时光总嘲笑我的痴心妄想 提交于 2019-12-05 20:55:02

This is how I would solve it: http://jsfiddle.net/77bMx/86/

  • Handles numpad input as well as standard number keys
  • Works with backspace
  • Will revert to 0.00 if you somehow manage to produce illegal input (like backspacing too much)

The basic idea is to intercept any input to the box, make sure it's of the correct type (a number, or a backspace) and then add it to a backing storage string (var input), and then format that string to display correctly. The user never directly enters anything into the text box, since I use return false at the end of the event handler.

Well, the code for processing the input can easily be made like this:

$("#number").keyup(function(e){
    var number = $("#number").val();
    var newValue = (Math.round(parseFloat(number)*100)/100)/100;
});

It might be a challenge getting it back into the textbox without getting conflicts, but you could 'fake' it by doing something like this:

http://jsfiddle.net/AnfCn/1/

Disclaimer: Quick and dirty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!