There's a function in javascript specifically for, among other things, doing math, eval(). It's use is generally discouraged because it takes/expects a string and converts it into a function or expression as best it can. As a result it's prone to errors of unexpected type conversion and/or incorrect quoting. That said, this works in Firefox at least, probably all others:
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function basicmath(a, b, c){
return eval(a + b + c);
}
</script>
</head>
<body>
<input type="button" onclick="alert(basicmath(4, '+', 3));" value="4 plus 3"><br>
<input type="button" onclick="alert(basicmath(4, '/', 3));" value="4 over 3"><br>
<input type="button" onclick="alert(basicmath(4, '-', 3));" value="4 minus 3"><br>
<input type="button" onclick="alert(basicmath(4, '*', 3));" value="4 times 3"><br>
</body>
</html>
For a little more fun, try this variation:
Code:
function basicmath(a, b, c){
return [a, b, c, '= '].join(' ') + eval(a + b + c);
}
Bookmarks