我使用下面的JS来去除逗号,破折号和任何非数字字符。但是,如果我说“ ---”,那么该数字仍然不能正确添加,而是变为负数。这让我难过。谁能看到发生了什么事?谢谢,它在var result
块中。
var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_total_retail_amount');
var $totalRetailAmountFieldLabel = $('label[for=am_total_retail_amount]');
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
//Calculate One time cost and total recurring cost
function calcTotalRetailVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1.replace(/(,|[^\d.-]+)+/g, '')) + parseFloat(num2.replace(/(,|[^\d.-]+)+/g, ''));
if (!isNaN(result)) {
$totalRetailAmountField.text('$' + result.toFixed(2));
}
}
calcTotalRetailVal();
$oneTimeCostField.on("keydown keyup", function() {
calcTotalRetailVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcTotalRetailVal();
});