JavaScript:函数不能正确格式化数字

时间:2017-05-04 07:36:21

标签: javascript

我有一个函数,每隔4个数字放入逗号,以便格式化为货币。问题是前4个数字不会添加逗号,它只会在输入空格时正确格式化所有内容。另外,为什么我的输入允许在我设置时不输入空格键?谢谢!

   <script>
    //Gets the value of the key that was pressed
      function keypress(e){
                var z="";
                var minStr = document.getElementById('min').value;
                var charval = String.fromCharCode(e.keyCode);
                var backspaceKey = String.fromCharCode(8);
                var tabKey = String.fromCharCode(9);
                var enterKey = String.fromCharCode(13);
                var spaceBarKey = String.fromCharCode(32);
    //Validates that only numbers and specific types of keys can be entered
                if(         isNaN(charval) &&
                            charval != backspaceKey &&
                            charval != tabKey &&
                            charval != enterKey &&
                            charval == spaceBarKey){
                    return false;
                }
                //Start of the function that adds commas
                if(minStr.length > 1 
                  && charval != backspaceKey
                  && charval != tabKey
                  && charval != enterKey
                  ){

//adds commas to the string
                    minStr = minStr.replace(/\D/g, "");
                    var minArray = minStr.split("");
                    var j = 0;
                    for(var i = minStr.length; i > 0; i--){
                        if(j == 3){
                            minArray.splice(i, 0, ",");
                            j = 0;
                        }
                        j++;
                    }
                    minArray = minArray.join("");
                    document.getElementById('min').value = minArray;
//Here is where it adds a comma to the first 4 numbers
                    if(minStr.length == 4){
                        var minArray = minStr.split("");
                        minArray.splice(1, 0, ",");
                        minArray = minArray.join("");
                        document.getElementById('min').value = minArray;
                    }
                }   
            }
    </script>
    <body>

      <input type="text" name="min" id="min" class="mini" onkeydown="return keypress(event)" placeholder="Enter the Min">
      <input type="text" name="max" id="max" onkeydown="return keypress(event)" placeholder="Enter the Max">

    </body>

DEMO:https://jsfiddle.net/efoc/dtqfLp05/

1 个答案:

答案 0 :(得分:0)

我已更新您的代码 -

keydown--> keyup

String.fromCharCode(e.keyCode)--> e.keyCode(used direct keycode)

检查 -   https://jsfiddle.net/dtqfLp05/1/