我正在尝试制作一个像这样的简单计算器:
输入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>
最佳答案
首先知道您想为应用程序使用什么语言。
我看到您使用PHP,HTML,JavaScript和jQuery。
但是,如果您重新考虑小型应用程序,您可能会注意到,您可以在客户端执行所有操作。这样您就可以丢弃PHP。
因此,现在我们需要HTML来显示表单。
<form>
<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="" />
</td>
<td>
<select id="oper" name="oper">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
</td>
<td>
<input id="val2" type="text" name="val2" value="" />
</td>
<td>
<input id="result" type="text" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>
<input type="submit" />
</td>
</tr>
</table>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
在您的HTML中,我编辑了一些内容:
我添加了
input type="submit"
,我们不能假设用户不能发送该表单。我也会更改您选择框的值
现在表格已经准备好了。
在对jQuery有一点了解的情况下,我们可以轻松地捕获Submit事件。
$('form').submit(onFormSubmit)
function onFormSubmit() {
var val1 = $('#val1').val()
var val2 = $('#val2').val()
var operator = $('#oper').val()
$('#result').val(eval(val1 + operator + val2))
return false
}
上面解释过,我有一个来自的事件监听器。
提交后,我得到3个值。
我使用eval将字符串用作代码,这样我就可以执行
eval(val1 + operator + val2)
我希望这能帮到您。
包含jsFiddle example here。
关于php - PHP做一个简单的计算器-代码不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15226750/