2

我需要将具有货币格式的输入字段与总输入相加。当它只有数字时,我可以让它工作。这是我的小提琴: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;
}

如果你们在小提琴中回复,将不胜感激。

4

2 回答 2

2

您需要删除数字中的逗号,以便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);
            }

工作小提琴

于 2013-06-21T14:22:49.263 回答
1

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

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

这是货币格式的样本

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

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

于 2013-06-22T00:31:15.440 回答