我正在尝试制作一个像这样的简单计算器:
输入1 选择输入2 = 输入3
- input1,input2 是第一个和第二个值
- 选择有 4 个运算符:+ - * /
- input3 显示结果
这是我的代码,它没有按预期工作,有人可以帮我吗?
<?php
ini_set('display_errors', 0);
session_start();
/* Check if form is submit
* if any input field is empty --> "NaN" result
* else check value of select field --> do the math --> result
* Then call JS function to change value of result field
*/
if(isset($_GET['act']) && $_GET['act']== 'do') {
$val1 = $_GET['val1'];
$val2 = $_GET['val2'];
$oper = $_GET['oper'];
if($val1 == NULL || $val2 == NULL)
$result= "NaN";
else {
switch($oper) {
case 1 : $result= $val1 + $val2; break;
case 2 : $result= $va1l - $val2; break;
case 3 : $result= $val1 * $val2; break;
case 4 : $result= $val1 / $val2; break;
}
}
echo "<script> showResult('".$result."') </script>";
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style>
input,select { height:30px;width:50px}
</style>
</head>
<body>
<form method="GET" action="bai4_1.php?act=do">
<table>
<tr><td>Op1</td>
<td>Oper</td>
<td>Op2</td>
<td>Result</td></tr>
<tr><td><input id="val1" type="text" name="val1" value="<?php echo
$_GET['val1'];?>"/></td>
<td><select id="oper" name="oper">
<option value=1>+</option>
<option value=2>-</option>
<option value=3>*</option>
<option value=4>/</option>
</select></td>
<td><input id="val2" type="text" name="val2" value="<?php
echo$_GET['val2'];?>"/> =</td>
<td><input id="result" type="text"></td></tr>
</table>
</form>
</body>
</html>
<script>
$("input,select").change(function(){
setTimeout(function(){
$("form").submit();
},1000);
});
function showResult(result) {
$("#result").val(result);
}
</script>