I'm not sure about key presses(my puzzle for tonight) but, does this seem reasonable?
<html><head>
<script>
function calculate(type) {
try{
var one, two, total;
one = parseInt(document.getElementById("num1").value);
two = parseInt(document.getElementById("num2").value);
switch (type) {
case 'add':
total = one + two;
break;
case 'subtract':
total = one - two;
break;
case 'multiply':
total = one * two;
break;
case 'divide':
total = one / two;
break;
}
if(isNaN(total)){
document.getElementById("demo").innerHTML = "Please enter numbers only";
}
else{
document.getElementById("demo").innerHTML = total;
return false;
}
}
catch(err){
document.getElementById("demo").innerHTML = "Something when wrong try later";
}
}
</script></head><body>
<input type="text" id="num1"> <br>
<input type="text" id="num2"> <br>
<input type="submit" value="+" onclick="calculate('add');return false;">
<input type="submit" value="-" onclick="calculate('subtract');return false;">
<input type="submit" value="*" onclick="calculate('multiply');return false;">
<input type="submit" value="/" onclick="calculate('divide');return false;">
<p id="demo"></p>
</body>
</html>
Although thinking about it as pbismad has mention and nogdog has eluded to, perhaps some better way of displaying a catch error would be better?
Oh and yes I just worked around dale's code, for some reason I didn't think switch was in JavaScript :rolleyes: