2011-12-01 20 views
1

我有這個代碼,它適用於添加輸入框工作正常。Jquery,爲便士和英鎊添加輸入框總計與單獨的輸入框

$.fn.sumValues = function() { 
var sum = 0; 
this.each(function() { 
    if ($(this).is(':input')) { 
     var val = $(this).val(); 
    } else { 
     var val = $(this).text(); 
    } 
    sum += parseFloat(('0' + val).replace(/[^0-9-\.]/g, ''), 10); 
    sum = Math.round(sum*Math.pow(10,2))/Math.pow(10,2); 
}); 
return sum; 
}; 

$(document).ready(function() { 
$('input.money1').bind('keyup', function() { 
    $('#totalsales').html($('input.money1').sumValues()); 
}); 

}); 

但是,我想單獨爲英鎊/便士(money1代表磅箱和money2代表便士)。我曾嘗試加入

$('input.money2').bind('keyup', function() { 
    $('#totalsales2').html($('input.money2').sumValues()); 
}); 

但正如你可以告訴這將增加他們,其他100,反正是有我可以使它加1 totalsales爲每一百?

的jsfiddle - http://jsfiddle.net/RZrTa/

回答

1

會用的jsfiddle作爲即時通訊不是100%肯定你的意思更好。如果可以設置一個例子,它將有助於得到你的答案。

但是,如果你想要做的是採取便士價值,每100便士加1磅,然後像

//-- get the pennies 
var pence = $('input.money2').sumValues(); 

//--- get the pounds in those pennies 
var addtopounds = Math.floor(pence/100); 

//-- for each pound, remove 100 pennies 
pence -= addtopounds*100; 

//-- now pence is what you stick in the total pence box 
//-- and then the addtopounds number needs to be added to 
//-- the value of the total pounds 
+0

繼承人jsfiddle - http://jsfiddle.net/RZrTa/ –

+1

http://jsfiddle.net/RZrTa/4/ – Lee

+0

看起來不錯,唯一的問題是,如果他們最後輸入一個磅值,它將失去從便士中增加的磅數值。 –