代碼如下:
<html>
<head><title>單價數量求和</title></head>
<body>
<table align="center" border="1" width="650">
<tr><td align="center" colspan="4"><b>訂單</b></td></tr>
<tr>
<td align="center" width="50"><b>名稱</b></td>
<td align="center" width="200"><b>單價</b></td>
<td align="center" width="200"><b>數量</b></td>
<td align="center" width="200">
<input type="button" value="總價" onclick="pay();" />
</td>
</tr>
<tr>
<td align="center">U盤</td>
<td align="center"><input id="objectPrice" type="text" width="195" /></td>
<td align="center"><input id="objectNum" type="text" width="195" /></td>
<td align="center"><input id="objectPay" type="text" width="195" readOnly="true" /></td>
</tr>
</table>
<script type="text/javascript">
function pay() {
var resultPrice = document.getElementById("objectPrice").value;
var resultNum = document.getElementById("objectNum").value;
if(resultPrice == "") {
alert("物品單價不能為空!");
document.getElementById("objectPay").value = "";
return false;
}
if(isNaN(resultPrice) || resultPrice < 0) {
alert("非法的商品單價!");
document.getElementById("objectPay").value = "";
return false;
}
if(resultNum == "") {
alert("物品數量不能為空!");
document.getElementById("objectPay").value = "";
return false;
}
if(!checkNum(resultNum)) {
alert("非法的商品數量!");
document.getElementById("objectPay").value = "";
return false;
}
var resultPay = parseFloat(resultPrice)*parseInt(resultNum);
document.getElementById("objectPay").value = resultPay;
}
function checkNum(num) {
var re = /^\d+$/;
return re.exec(num) != null;
}
</script>
</body>
</html>