我有一个具有以下输入的表格:
<input type="text" name="amount" id="amount" maxlength="10" onblur="applyInterest();" />
<input style="width:60px" type="text" name="interest" id="interest" maxlength="6" placeholder="Interest" onkeyup="applyInterest();" /> %
<input type="text" name="total_amount" id="total-amount" maxlength="10" readonly />
function applyInterest()
{
var amount = parseInt(document.getElementById('amount').value);
var interest = parseInt(document.getElementById('interest').value);
var int_amount = Math.round((interest/100)*amount);
document.getElementById('total-amount').value = (amount + int_amount);
}
服务器端代码:
$amount = trim($_POST['amount']);
$interest_per = trim($_POST['interest']);
$total_amount = trim($_POST['total_amount']);
$error = array();
if ( ! preg_match('/^[1-9][0-9]*(\.[0-9]{1,2})?$/', $amount)) {
$error[] = 'Invalid amount';
}
if ( ! preg_match('/^[1-9][0-9]*(\.[0-9]{1,2})?$/', $total_amount)) {
$error[] = 'Invalid total amount';
}
if ( ! empty($interest_per)) {
if ( ! preg_match('/^[1-9][0-9]*(\.[0-9]{1,2})?$/', $interest_per)) {
$error[] = 'Invalid interest';
}
} else {
$interest_per = 0;
}
if ( empty($error)) {
$int_amt = round(($interest_per / 100) * $amount);
$chk_total_amt = $amount + $int_amt;
if ($chk_total_amt != $total_amount) {
$error[] = "Interest plus amount is not matching total amount";
}
}
if ( ! empty($error)) {
$message = array('status' => 422, 'data' => $error);
$conn = null;
echo json_encode($message);
exit();
}
金额,利息金额,每笔利息和总金额以2精度存储为数字。 (PostgreSQL)。
现在我的问题是:
用于客户端代码演示的JS Fiddle链接:https://jsfiddle.net/deepakthakur07/dnyrf6gt/2/