如何自动求和输入字段与货币格式

How to auto sum input fields with currency format

本文关键字:货币 格式 字段 输入 何自动 求和      更新时间:2023-09-26

我需要将货币格式的输入字段求和为总输入。只要是数字,我就能搞定。这是我的小提琴:http://jsfiddle.net/nobuts/F2wEK/2/

onKeyUp自动逗号功能工作正常,但不能再求和这些数字了。这是我的JS:

$(document).ready(function(){
$(".cost").each(
    function(){
    $(this).keyup(
        function(){
        calculateSum()
            });
        });
    });
    function calculateSum(){
        var sum=0;
        $(".cost").each(
        function(){
            if(!isNaN(this.value)&&this.value.length!=0){
                sum+=parseFloat(this.value);
                }
            });             
        $("#sum").val(sum.toFixed(2));
        }
$(document).ready(function(){
  $('input.cost').keyup(function(event){
  // skip for arrow keys
  if(event.which >= 37 && event.which <= 40){
  event.preventDefault();
  }
  var $this = $(this);
  var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
  var num2 = RemoveRougeChar(num.replace(/(.
3})/g,"$1,").split("").reverse().join(""));     
  console.log(num2);

  // the following line has been simplified. Revision history contains original.
  $this.val(num2);  
});});
function RemoveRougeChar(convertString){   
if(convertString.substring(0,1) == ","){
    return convertString.substring(1, convertString.length)            
}
return convertString;
}

如果你们能及时回复,我将不胜感激。

您需要删除数字中的逗号,以便isNaN()将其识别为数字,因此,替换以下代码:

        if(!isNaN(this.value)&&this.value.length!=0){
            sum+=parseFloat(this.value);
        }

:

            var vl = this.value.replace(',','');
            if(!isNaN(vl) && vl.length!=0){
                sum+=parseFloat(vl);
            }

参见working fiddle

我只是开发插件,使它更容易,试试这个

http://www.xsanisty.com/calx/

,这里是货币格式的示例

http://prototype.xsanisty.com/calx/sample/roi.html

http://prototype.xsanisty.com/calx/sample/calx_custom_language.html