在这个简单的 html 页面中,我有一个 JavaScript 可以在用户选择运输方式时进行计算,问题是在 $_POST 之后计算不会保持不变,即使由于我添加的简单 PHP 代码用户选择保持不变,我对 PHP 和 JavaScripts 都是全新的,在几次失败后,我想你们可以帮助我,谢谢。
<html>
<body>
<div class="calculations">
<table>
<tbody><tr>
<td>Subtotal:</td>
<td id="subtotal">$97.00</td>
</tr>
<tr>
<td>Shipping:</td>
<td id="shipping">$6.95</td>
</tr>
<tr class="total">
<td>Total:</td>
<td id="total">$103.95</td>
</tr>
</tbody></table></div>
<select name="shippingmethod" onchange="calc()" class="shipping-method" id="shippingmethod">
<option value="" selected="<?php if (!$_POST || $shippingmethod == '0') {echo 'selected';} ?>">USPS Ground - $6.95</option>
<option value="1" <?php if ($_POST && $shippingmethod == '1') {echo 'selected';}?>>Priority Shipping - $17.95</option>
</select>
<script>
function calc() {
var subtotal =parseFloat(document.getElementById("subtotal").innerHTML.substring(1));
var shipping = parseInt(document.getElementById("shippingmethod").value);
if(shipping == 1) {
var total = subtotal+17.95;
document.getElementById("shipping").innerHTML = "$"+17.95;
} else {
var total = subtotal+6.95;
document.getElementById("shipping").innerHTML = "$"+6.95;
}
document.getElementById("total").innerHTML = "$"+total;
}
document.getElementById("shippingmethod").onchange = function(){
window.scrollTo(0, 0); // scroll to top
calc(); // call function
};
</script>
</body>
<html>