I am a beginner and trying to write a simple Calculator in Javascript but something is wrong.
When the user enters numbers, "Number 1" and "Number 2", then the following should occur for addition, subtraction, multiply and division (for example):
Number1 = 5, Number2 = 3
then => 5 + 3 = 8,
5 - 3 = 2,
5 * 3 = 15,
5 / 3 = 1.6
When the user gives numbers to specific equation, then displays the result of these operations.
<html>
<head>
<title>Function Calculator</title>
<script type="text/javascript">
function show_cal(){
function num(){
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a+b;
document.form1.result1.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a-b;
document.form1.result2.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a*b;
document.form1.result3.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a/b;
document.form1.result4.value=c;
}
function addition(){
a=Number(document.form1.num3.value);
b=Number(document.form1.num4.value);
c=a+b;
document.form1.result1.value=c;
}
function subtraction(){
a=Number(document.form1.num5.value);
b=Number(document.form1.num6.value);
c=a-b;
document.form1.result2.value=c;
}
function multiply(){
a=Number(document.form1.num7.value);
b=Number(document.form1.num8.value);
c=a*b;
document.form1.result3.value=c;
}
function division(){
a=Number(document.form1.num9.value);
b=Number(document.form1.num10.value);
c=a/b;
document.form1.result4.value=c;
}
/*function formValidator(){
var number = document.getElementById('number');
if(isNumeric(number, "Only Numbers pls")){
return true;
}return false;
}
function notEmpty(elem, helperMsg){ //gia keno
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function show_clear(){
document.form1.display.value=null;
num1= null;
num2 = null;
lastaction= null;
action = null;
} */
}
</script>
</head>
<body>
<table width="400" align="center" bgcolor="#C0C0C0">
<form name="form1" action="">
<tr align="center">
<td width="600" height="112" align="center" border="1">
<h1 align="center"> Calculator </h1>
Number 1: <input name="num1" type="text" size=10/>
Number 2: <input name="num2" type="text" size=10/>
</td>
</tr>
<tr align="center">
<td width="500">
<input name="num3" type="text" size=10/> +
<input name="num4" type="text" size=10/> =
<input name="result1" type="text" size=10/>
</td>
</tr>
<br/>
<tr align="center">
<td width="500">
<input name="num5" type="text" size=10/> -
<input name="num6" type="text" size=10/> =
<input name="result2" type="text" size=10/>
</td>
</tr>
<br/>
<tr align="center">
<td width="500">
<input name="num7" type="text" size=10/> *
<input name="num8" type="text" size=10/> =
<input name="result3" type="text" size=10/>
</td>
</tr>
<br/>
<tr align="center">
<td width="500">
<input name="num9" type="text" size=10/> /
<input name="num10" type="text"size=10/> =
<input name="result4" type="text" size=10/>
</td>
</tr>
<br/>
<td height="13"></tr>
<tr align="center" width="100">
<td>
<input name="result" type="button" onClick="show_cal()" value="Result" />
<input type="button" onClick="show_clear()" value="Clear"/>
</td>
</tr>
</form>
</table>
</body>
</html>
the problem is you have a function sum within a function show_calc and you don't call this function.
You need call the function num when finish the showcalc function.
<script type="text/javascript">
function show_cal(){
function num(){
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a+b;
document.form1.result1.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a-b;
document.form1.result2.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a*b;
document.form1.result3.value=c;
a=Number(document.form1.num1.value);
b=Number(document.form1.num2.value);
c=a/b;
document.form1.result4.value=c;
}
function addition(){
a=Number(document.form1.num3.value);
b=Number(document.form1.num4.value);
c=a+b;
document.form1.result1.value=c;
}
function subtraction(){
a=Number(document.form1.num5.value);
b=Number(document.form1.num6.value);
c=a-b;
document.form1.result2.value=c;
}
function multiply(){
a=Number(document.form1.num7.value);
b=Number(document.form1.num8.value);
c=a*b;
document.form1.result3.value=c;
}
function division(){
a=Number(document.form1.num9.value);
b=Number(document.form1.num10.value);
c=a/b;
document.form1.result4.value=c;
}
num();
}
But I better ways to make this correctly.
Your code could be cleaner and violates DRY (Don't Repeat Yourself) repeatedly.
Try this:
<form action="javascript:void(null);" method="post" onSubmit="calculate(this);">
<p><label>Number 1: <input type="number" /></label></p>
<p><label>Number 2: <input type="number" /></label></p>
<p><input type="submit" value="Calculate" /></p>
<p>N1 + N2 = <span>-</span></p>
<p>N1 - N2 = <span>-</span></p>
<p>N1 * N2 = <span>-</span></p>
<p>N1 / N2 = <span>-</span></p>
</form>
<script type="text/javascript">
function calculate(form) {
var fc = form.children,
n1 = parseInt(fc[0].children[0].children[0].value || 0,10),
n2 = parseInt(fc[1].children[0].children[0].value || 0,10);
fc[3].children[0].firstChild.nodeValue = n1+n2;
fc[4].children[0].firstChild.nodeValue = n1-n2;
fc[5].children[0].firstChild.nodeValue = n1*n2;
fc[6].children[0].firstChild.nodeValue = n1/n2;
}
</script>
JSFiddle demonstration
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<link rel="stylesheet" href="cal.css">
<script src="./calc.js"></script>
</head>
<body>
<div class="calculator">
<div id="textBox1">
<input type="text"id="textBox" placeholder="0"/>
</div>
<div class="buttons">
<button class="calc-buttons" onclick="disPlay('1')" value="1">1</button>
<button class="calc-buttons" onclick="disPlay('2')" value="2">2</button>
<button class="calc-buttons" onclick="disPlay('3')" value="3">3</button>
<button class="calc-buttons" onclick="disPlay('4')" value="4">4</button>
<button class="calc-buttons" onclick="disPlay('5')" value="5">5</button>
<button class="calc-buttons" onclick="disPlay('6')" value="6">6</button>
<button class="calc-buttons" onclick="disPlay('7')" value="7">7</button>
<button class="calc-buttons" onclick="disPlay('8')" value="8">8</button>
<button class="calc-buttons" onclick="disPlay('9')" value="9">9</button>
<button class="calc-buttons" onclick="disPlay('0')" value="0">0</button>
<button class="calc-buttons" onclick="disPlay('+')" value="+">+</button>
<button class="calc-buttons" onclick="disPlay('-')" value="-">-</button>
<button class="calc-buttons" onclick="disPlay('*')" value="*">*</button>
<button class="calc-buttons" onclick="disPlay('/')" value="/">/</button>
<button class="calc-buttons" onclick="disPlay('%')" value="%">%</button>
<button class="calc-buttons" onclick="clr()" value="clear">C</button>
<button class="calc-buttons" onclick="disPlay('.')" value=".">.</button>
<button class="calc-buttons" onclick="backSpace()" value="B">B</button>
<button class="calc-buttons-equal" onclick="result()" value="=">=</button>
</div>
</div>
</body>
</html>
calc.js:---
var res = "";
function disPlay(x) {
nan = document.getElementById("textBox").value;
if (nan === "NaN" || nan === "Infinity" || nan === "undefined" || nan === "-Infinity") { // delete Nan,infinity,undefined after entering the numbers.
document.getElementById("textBox").value = "";
}
if (res && (x >= 0 || x <= 0)) {
res = false;
document.getElementById("textBox").value = "";
document.getElementById("textBox").value += x;
} else {
document.getElementById("textBox").value += x;
res = false;
var y = [];
y = document.getElementById("textBox").value;
p = y.length;
if ((y[p - 2] === "*" || y[p - 2] === "/" || y[p - 2] === "%" || y[p - 2] === "+" || y[p - 2] === "-" || y[p - 2] === ".") && (x === "*" || x === "/" || x === "%" || x === "+" || x === "-" || x === ".")) {
document.getElementById("textBox").value = y.slice(0, p - 1);
}
}
}
function clr() {
document.getElementById("textBox").value = "";
}
function backSpace() {
bakSpa = document.getElementById("textBox").value;
if (bakSpa === "NaN" || bakSpa === "Infinity" || bakSpa === "undefined" || bakSpa === "-Infinity") {
document.getElementById("textBox").value = "";
} else {
var value = document.getElementById("textBox").value;`enter code here`
document.getElementById("textBox").value = value.substr(0, value.length - 1);
}
}
function result() {
exp = "";
exp = document.getElementById("textBox").value;
l = exp.length;
if (exp[0] == '*' || exp[0] == '/' || exp[0] == '%' || exp[0] == '+' || exp[l - 1] == '+' || exp[l - 1] == '%' || exp[l - 1] == '/' || exp[l - 1] == '*' || exp[l - 1] == '-') {
document.getElementById("textBox").value = 'NaN';
} else {
exp = document.getElementById("textBox").value;
res = eval(exp);
console.log(res);
document.getElementById("textBox").value = res;
if(res===undefined){
document.getElementById("textBox").value = "";
}
}
}
cal.css:-
*{
box-sizing: border-box;
text-align: center;
padding: 0;
margin: 0;
}
::placeholder {
color: red;
opacity: 1;
}
body {
background: #F6F6F6;
}
.calculator {
max-width: 400px;
margin: 0 auto;
border: 2px solid #111;
border-radius: 5px;
display:flex;
flex-wrap: wrap;
flex: 0 1 60%;
min-width:400px;
color: #F6F6F6;
}
#calc-buttons ,.calc-buttons {
background-color: gray;
border: none;
color: white;
padding-left: 60px;
padding-top: 15px;
text-decoration: none;
display: inline-flex;
font-size: 16px;
margin: 1px;
cursor: pointer;
width:125px;
height: 50px;
border-radius: 6px;
}
.calc-buttons-equal{
background-color:orange;
border: none;
color: white;
padding-left: 190px;
padding-top: 15px;
text-decoration: none;
display: inline-flex;
font-size: 16px;
margin: 1px;
cursor: pointer;
width:388px;
height: 50px;
border-radius: 6px;
}
#textBox1 input {
background: none;
border: none;
box-shadow: none;
padding: 10px;
width: 100%;
border-bottom: 2px solid #111;
color: #333;
text-align: right;
font-size: 40px;
border-radius: 0;
}
I created an api to make a calculator automatically, just put the api inside script tag (<script src="https://calculatorapi.netlify.app/api.js>"). I created this api to help more people build their own web apps. If you want to style my api calculator just do:
<style>
<!--To result input-->
input[type="text"] {
<!--Your style-->
}
<!-- To Calculator buttons e.g: 1,2,3 -->
input[type="buttons"] {
<!-- Your style -->
}
</style>
<!DOCTYPE html>
<html>
<head>
<script>
z="";
fun =""
ans="";
function dis(val)
{
ans = document.getElementById("result").value;
if (ans === "Infinity" ||ans === "-Infinity" || ans === "undefined") {
document.getElementById("result").value = "";
}
if(z&& (val >= 0 || val <= 0)){
z = false;
document.getElementById("result").value="";
document.getElementById("result").value+=val;
}
else{
ans = document.getElementById("result").value+=val;
z = false;
var y = [];
y = document.getElementById("result").value;
p = y.length;
if ((y[p - 2] ==="*" ||y[p - 2] ==="/" ||y[p - 2] ==="%" ||y[p - 2] ==="+" ||y[p - 2] ==="-" ||y[p - 2] ===".") && (val ==="*" ||val ==="/" ||val ==="%" ||val ==="+" ||val ==="-" ||val ===".")) {
document.getElementById("result").value = y.slice(0, p - 2)+y[p-1];
}
}
}
function solve()
{
let i,j;
i= ans;
j=i[i.length-1];
if(i[0]==="*"||i[0]=="/"||i[0]==="%"||i[0]==="+"){
document.getElementById("result").value = undefined;
}
else if(j==="*"||j==="/"||j==="%"||j==="."||j==="+"||j==="-"){
document.getElementById("result").value = undefined;
}
else {
z="";
let x = document.getElementById("result").value;
z = eval(x);
if(z===undefined)
{
document.getElementById("result").value = "";
}
else{
document.getElementById("result").value = z;
}
}
}
function clr()
{
document.getElementById("result").value =""
}
function back()
{
var i = document.getElementById("result").value;
if(i==="undefined"||i==="infinity"||i==="-infinity"){
document.getElementById("result").value ="";
}
else{
document.getElementById("result").value = i.substr(0, i.length - 1);
}
}
</script>
<style>
* {
background-color: black;
height: 100%;
width: 100%;
margin: 0px;
text-align: center;
box-sizing: border-box;
}
.disply{
height: 30%;
width: 100%;
box-sizing: border-box;
}
.functions{
height: 68%;
width: 100%;
box-sizing: border-box;
}
input{
background-color:black;
border:whitesmoke;
color: white;
text-align: center;
font-size: 45px;
cursor: pointer;
height: 20%;
width: 24.2%;
}
button{
background-color:lightslategray;
color: white;
text-align: center;
font-size: 90px;
cursor: pointer;
height: 18%;
width: 24%;
border: none;
border-radius: 50%;
}
button[type=button4]{
width: 48.4%;
padding-right: 24.2%;
border-radius: 40%;
}
button[type=button2]{
background-color: orange;
font-size: 60px;
}
button[type=button1]{
background-color: whitesmoke;
color: black;
font-size: 60px;
}
input[type=text]{
height: 100%;
width: 100%;
background-color:black;
text-align: right;
color: white;
font-size: 100px;
}
::placeholder{
color: bisque;
}
</style>
</head>
<body>
<div class="disply">
<input type="text" id="result" placeholder="0"/>
</div>
<div class="functions">
<button type="button1" value="AC" onclick="clr()">AC</button>
<button type="button1"value="/" onclick="dis('/')">/</button>
<button type="button1"value="%" onclick="dis('%')">%</button>
<button type="button2"value="back" onclick="back()">back</button>
<button type="button3"value="7" onclick="dis('7')">7</button>
<button type="button3"value="8" onclick="dis('8')">8</button>
<button type="button3"value="9" onclick="dis('9')">9</button>
<button type="button2"value="*" onclick="dis('*')">*</button>
<button type="button3"value="4" onclick="dis('4')">4</button>
<button type="button3"value="5" onclick="dis('5')">5</button>
<button type="button3"value="6" onclick="dis('6')">6</button>
<button type="button2"value="-" onclick="dis('-')">-</button>
<button type="button3"value="1" onclick="dis('1')">1</button>
<button type="button3"value="2" onclick="dis('2')">2</button>
<button type="button3"value="3" onclick="dis('3')">3</button>
<button type="button2"value="+" onclick="dis('+')">+</button>
<button type="button4"value="0" onclick="dis('0')">0</button>
<button type="button3"value="." onclick="dis('.')">.</button>
<button type="button2"value="=" onclick="solve()">=</button>
</div>
</body>
</html>
Related
i would like create a table, where one column would be variables and i want to have "+" and "-" buttons next to it. So when i click button "+" it would show number input and after submit, it would add to the value.
It works for one value, but do not get the other right, without copying whole script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table</title>
</head>
<style>
body {
background-color: lightslategray;
}
#PLA {
float: left;
width: 30%;
padding: 10px;
}
th, td {
border: 1px solid;
}
.header {
text-align: center;
font-size: 20px;
}
.celltext {
font-size: 15px;
}
.number {
text-align: center;
}
.vbutton {
background-color: gray;
border: 1px solid black;
border-radius: 6px;
color: white;
text-align: center;
text-decoration: none;
font-size: 10px;
padding: 0px;
margin-right: 4px;
width: 20px;
height: 20px;
float: right;
}
button:hover {
background-color: lightgray;
color: black;
}
.input {
padding: 0px;
width: 48px;
height: 16px;
font-size: 14px;
-webkit-appearance: none;
}
input[type = number] {
-moz-appearance: textfield;
}
input:focus {
border: 0px;
outline: 0px;
}
</style>
<body>
<table id="PLA">
<div>
PLA
<span id="test"></span>
<input type="number" class="input" id="nwpla" onchange="changewpla1()" onkeypress="return onlyNumberKey(event)">
</div>
<tr class="header">
<td>Barva</td>
<td>Výrobce</td>
<td>Hmotnost (g)</td>
<td>Cena (kg)</td>
</tr>
<tr class="celltext">
<td>černá <div class="box black"></div></td>
<td>Polymaker PolyLite</td>
<td class="number" id="pla1">
<span id="wpla1"></span>
<button class="vbutton" onclick="addpla()"> + </button>
<button class="vbutton" onclick="subpla()"> - </button>
</td>
<td class="number">
800
</td>
</tr>
<tr class="celltext">
<td>černá <div class="box black"></div></td>
<td>Polymaker PolyLite</td>
<td class="number" id="pla2">
<span id="wpla2"></span>
<button class="vbutton" onclick="addpla()"> + </button>
<button class="vbutton" onclick="subpla()"> - </button>
</td>
<td class="number">
800
</td>
</tr>
</table>
</body>
<script>
// test
test = document.getElementById("test");
// Weight of pla1
wpla1 = document.getElementById("wpla1");
nwpla = document.getElementById("nwpla");
nwpla.style.display = "none";
var pla1weight = localStorage.pla1weight;
localStorage.setItem("pla1weight", pla1weight);
if (localStorage.pla1weight == "undefined" || localStorage.pla1weight == isNaN) {
localStorage.pla1weight = 0
pla1weight = 0;
wpla1.innerHTML = localStorage.pla1weight;
wpla1.value = localStorage.pla1weight;
}
else {
wpla1.innerHTML = localStorage.pla1weight;
wpla1.value = localStorage.pla1weight;
}
function changewpla1() {
x = parseInt(wpla1.value, 10);
y = parseInt(nwpla.value, 10);
if (p == 1) {
pla1weight = x - y;
} else {
pla1weight = x + y;
}
wpla1.innerHTML = pla1weight;
wpla1.value = pla1weight;
localStorage.setItem("pla1weight", pla1weight);
nwpla.style.display = "none";
}
// Weight of pla2
wpla2 = document.getElementById("wpla2");
nwpla = document.getElementById("nwpla");
nwpla.style.display = "none";
var pla2weight = localStorage.pla2weight;
localStorage.setItem("pla2weight", pla2weight);
if (localStorage.pla2weight == "undefined" || localStorage.pla2weight == isNaN) {
localStorage.pla2weight = 0
pla2weight = 0;
wpla2.innerHTML = localStorage.pla2weight;
wpla2.value = localStorage.pla2weight;
}
else {
wpla2.innerHTML = localStorage.pla2weight;
wpla2.value = localStorage.pla2weight;
}
function changewpla2() {
x = parseInt(wpla2.value, 10);
y = parseInt(nwpla.value, 10);
if (p == 1) {
pla2weight = x - y;
} else {
pla2weight = x + y;
}
wpla2.innerHTML = pla2weight;
wpla2.value = pla2weight;
localStorage.setItem("pla2weight", pla2weight);
nwpla.style.display = "none";
}
function addpla() {
nwpla.value = 0;
p = 0;
nwpla.style.display = "";
}
function subpla() {
nwpla.value = 0
p = 1;
nwpla.style.display = "";
}
function onlyNumberKey(evt) {
var ASCIICode = (evt.which) ? evt.which : evt.keyCode
if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
return false;
return true;
}
</script>
</html>
Any idea?
I would like to have a database as last option. Every value would be saved in local storage.
Thanks.
Incredibly novice coder here. Like, complete beginner aside from Tumblr and Neopets teaching me how to read and do basic tinkering.
I've maybe bitten off more than I can chew on this project, anybody willing to help?
Needing 5 buttons in a single column where "on click" the text changes. I got it to work for 1, but adding 5 on the same page all the buttons go random and I think they need individual IDs, but I have no idea how to do that.
<!DOCTYPE html>
<html>
<head>
<style>
.button {
background-color: #f0c640;
border: none;
color: #08365F;
padding: 32px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
margin: 4px 2px;
cursor: pointer;
font-family: 'Quattrocento Sans', sans-serif;
}
</style>
</head>
<body>
<center>
<input type="button" id= "bf3" class="button" value="BF₃" onclick="return change(this);" />
<script type="text/javascript">
function change( bf3 )
{
if (bf3.value === "BF₃" )
bf3.value = "boron trifluoride";
else
bf3.value = "BF₃";
}
</script>
</center>
</body>
</html>
<body>
<center>
<input type="button" id= "sf6" class="button" value="SF₆" onclick="return change(this);" />
<script type="text/javascript">
function change( sf6 )
{
if ( sf6.value === "SF₆" )
sf6.value = "sulfur hexafluoride";
else
sf6.value = "SF₆";
}
</script>
</center>
</body>
</html>
<body>
<center>
<input type="button" id="h2o" class="button" value="H₂O" onclick="return change(this);" />
<script type="text/javascript">
function change( h2o )
{
if ( h2o.value === "H₂O" )
h2o.value = "dihydrogen monoxide (aka water)";
else
h2o.value = "H₂O";
}
</script>
</center>
</body>
<body>
<center>
<input type="button" id="pcl5" class="button" value="PCl₅" onclick="return change(this);" />
<script type="text/javascript">
function change( pcl5 )
{
if ( pcl5.value === "PCl₅" )
pcl5.value = "phosphorus pentachloride";
else
pcl5.value = "PCl₅;
}
</script>
</center>
</body>
</html>
<body>
<center>
<input type="button" class="button" id="n2h4" value="N₂H₄" onclick="return change(this);" />
<script type="text/javascript">
function change( n2h4 )
{
if ( n2h4.value === "N₂H₄" )
n2h4.value = "dinitrogen tetrahydride";
else
n2h4.value = "N₂H₄;
}
</script>
</center>
</body>
</html>
I would do it like this for more maintainability:
var container = document.getElementById('container');
var molecules = [
{ formula: "BF₃", name: "boron trifluoride" },
{ formula: "SF₆", name: "sulfur hexafluoride" },
{ formula: "H₂O", name: "dihydrogen monoxide (aka water)" },
{ formula: "PCl₅", name: "phosphorus pentachloride" },
{ formula: "N₂H₄", name: "dinitrogen tetrahydride" }
];
molecules.forEach(function(m) {
var showName = false;
var btn = document.createElement('input');
btn.type = 'button';
btn.className = 'button';
btn.value = m.formula;
btn.addEventListener('click', function() {
showName = !showName;
btn.value = showName ? m.name : m.formula;
});
container.appendChild(btn);
container.appendChild(document.createElement('br'));
});
#container { text-align: center; }
.button {
background-color: #f0c640;
border: none;
color: #08365F;
padding: 32px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
margin: 4px 2px;
cursor: pointer;
font-family: 'Quattrocento Sans', sans-serif;
}
<div id="container"></div>
You do not need multiple functions to achieve that. Simply check the value of the currently clicked button and set the value accordingly.
Try the following way:
function change(currBtn){
if(currBtn.value == 'BF₃' || currBtn.value == 'boron trifluoride'){
if(currBtn.value == 'BF₃')
currBtn.value = 'boron trifluoride';
else
currBtn.value = 'BF₃';
}
else if(currBtn.value == 'SF₆' || currBtn.value == 'sulfur hexafluoride'){
if(currBtn.value == 'SF₆')
currBtn.value = 'sulfur hexafluoride';
else
currBtn.value = 'SF₆';
}
else if(currBtn.value == 'H₂O' || currBtn.value == 'dihydrogen monoxide (aka water)'){
if(currBtn.value == 'H₂O')
currBtn.value = 'dihydrogen monoxide (aka water)';
else
currBtn.value = 'H₂O';
}
else if(currBtn.value == 'PCl₅' || currBtn.value == 'phosphorus pentachloride'){
if(currBtn.value == 'PCl₅')
currBtn.value = 'phosphorus pentachloride';
else
currBtn.value = 'PCl₅';
}
else if(currBtn.value == 'N₂H₄' || currBtn.value == 'dinitrogen tetrahydride'){
if(currBtn.value == 'N₂H₄')
currBtn.value = 'dinitrogen tetrahydride';
else
currBtn.value = 'N₂H₄'
}
}
.button {
background-color: #f0c640;
border: none;
color: #08365F;
padding: 32px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
margin: 4px 2px;
cursor: pointer;
font-family: 'Quattrocento Sans', sans-serif;
}
<center>
<input type="button" id= "bf3" class="button" value="BF₃" onclick="change(this);" />
</center>
<center>
<input type="button" id= "sf6" class="button" value="SF₆" onclick="change(this);" />
</center>
<center>
<input type="button" id="h2o" class="button" value="H₂O" onclick="change(this);" />
</center>
<center>
<input type="button" id="pcl5" class="button" value="PCl₅" onclick="change(this);" />
</center>
<center>
<input type="button" class="button" id="n2h4" value="N₂H₄" onclick="change(this);" />
</center>
My way...
const buttonList =
[ [ 'BF₃', 'boron trifluoride' ]
, [ 'SF₆', 'sulfur hexafluoride' ]
, [ 'H₂O', 'dihydrogen monoxide (aka water)' ]
, [ 'PCl₅', 'phosphorus pentachloride' ]
, [ 'N₂H₄', 'dinitrogen tetrahydride' ]
];
buttonList.forEach(bt=>
{
let newbt = document.createElement('button')
, timOut = null;
newbt.className = 'button'
newbt.textContent = bt[0]
document.documentElement.appendChild( newbt )
newbt.onclick=()=>{
newbt.textContent = bt[1]
clearTimeout(timOut)
timOut = setTimeout(()=>{ newbt.textContent = bt[0] }, 1500)
}
})
/* or
buttonList.forEach(bt=>
{
let newbt = document.createElement('button')
, LibNum = 0
newbt.className = 'button'
newbt.textContent = bt[0]
newbt.onclick=()=>{ LibNum = ++LibNum %2; newbt.textContent = bt[LibNum] }
document.documentElement.appendChild( newbt )
})
*/
.button {
font-family: 'Quattrocento Sans', sans-serif;
font-size: 18px;
display: block;
margin: .2em auto;
padding: 1em;
color: #08365F;
background-color: #f0c640;
border: none;
cursor: pointer;
text-align: center;
min-width: 5em;
}
Did I still take the time to correct your code to help you?
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<title> sample code </title>
<style>
.button {
background-color: #f0c640;
border: none;
color: #08365F;
padding: 32px;
display: block; /* must be block to be centered */
font-size: 18px;
margin: 4px auto; /* this one replace <center> tag (obsolete) */
cursor: pointer;
font-family: 'Quattrocento Sans', sans-serif;
}
</style>
</head>
<body>
<input type="button" id="bf3" class="button" value="BF₃" onclick="xchange(this);" />
<input type="button" id="sf6" class="button" value="SF₆" onclick="xchange(this);" />
<input type="button" id="h2o" class="button" value="H₂O" onclick="xchange(this);" />
<input type="button" id="pcl5" class="button" value="PCl₅" onclick="xchange(this);" />
<input type="button" id="n2h4" class="button" value="N₂H₄" onclick="xchange(this);" />
<script>
function xchange( btn )
{
switch (btn.id) {
case 'bf3': btn.value = (btn.value==='BF₃') ? 'boron trifluoride' : 'BF₃'; break;
case 'sf6': btn.value = (btn.value==='SF₆') ? 'sulfur hexafluoride' : 'SF₆'; break;
case 'h2o': btn.value = (btn.value==='H₂O') ? 'dihydrogen monoxide (aka water)' : 'H₂O'; break;
case 'pcl5': btn.value = (btn.value==='PCl₅') ? 'phosphorus pentachloride' : 'PCl₅'; break;
case 'n2h4': btn.value = (btn.value==='N₂H₄') ? 'dinitrogen tetrahydride' : 'N₂H₄'; break;
} }
</script>
</body>
</html>
Today I started building a dummy client-side web app project in order to improve my basic JavaScript skills. Basically, it's a scientific calculator imitation that runs on line. As you'll see in the code, there are buttons in my HTML file each of which calls to one of the JavaScript functions in my JavaScript file. The calculator doesn't work, I mean, at all, and as I tried debugging, every function in my JavaScript file works by them-self as intended, but seemingly they don't work together.
Here's my code:
var currentMode = 'deg';
var screen = document.getElementById("screen");
var lastChar = screen.value.slice(-1);
/**
* Auxiliary functions
*/
function isNumeric(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
}
function sine(val) {
if (currentMode === 'deg') {
return Math.sin(Math.PI * val / 180);
}
return Math.sin(val);
}
function cos(val) {
if (currentMode === 'deg') {
return Math.cos(Math.PI * val / 180);
}
return Math.cos(val);
}
function tan(val) {
if (currentMode === 'deg') {
return Math.tan(Math.PI * val / 180);
}
return Math.tan(val);
}
function ln(val) {
return Math.log(val);
}
/**
* Calculator functions
*/
function addSpecial(val) {
var nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var operations = ['+', '-', '*', '/', '^'];
if (screen.value === '0') {
if (nums.indexOf(val) >= 0)
screen.value = val;
else if (val === '.' || operations.indexOf(val) >= 0)
screen.value += val;
else
screen.value = '0';
} else if (lastChar === '.' || operations.indexOf(lastChar) >= 0) {
if (val !== '.' && val !== '=' && operations.indexOf(val) < 0)
screen.value += val;
} else {
if (val !== '=')
screen.value += val;
else {
if (lastChar === '.' || operations.indexOf(lastChar) >= 0)
screen.value = 'SYNTAX ERROR!';
else if (screen.value.split('(') !== screen.value.split(')'))
screen.value = 'ERROR! Open or close parantheses!';
else {
try {
screen.value = eval(screen.value);
} catch(err) {
screen.value = err.message;
}
}
}
}
}
function setAngleMode(newMode) {
if (newMode === 'rad') {
if (currentMode === 'deg') {
currentMode = 'rad';
screen.value *= Math.PI / 180;
}
} else {
if (currentMode === 'rad') {
currentMode = 'deg';
screen.value *= 180 / Math.PI;
}
}
}
function addSymbol(val) {
switch (val) {
case 'pi':
screen.value = Math.PI;
break;
case 'e':
screen.value = Math.E;
break;
case 'phi':
screen.value = 1.61803398875;
break;
case 'gamma':
screen.value = 0.5772156649;
}
}
function clearScreen() {
screen.value = '';
}
function clearLast() {
screen.value.slice(0, -1);
}
function inverseVal() {
var len = screen.value.length;
var subs;
for (var i = 0; i < len; ++i) {
for (var j = len; j > i; --j) {
subs = screen.value.slice(i, j);
if (isNumeric(subs)) {
screen.value = 1 / parseFloat(subs);
break;
}
}
}
}
function addSquare() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^2';
}
}
function addPower() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^';
}
}
function addSquareroot() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^(1/2)';
}
}
function addRoot() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^(1/';
}
}
function addExp() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'Math.E^';
}
}
function addSin() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'sine(';
}
}
function addCos() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'cos(';
}
}
function addTan() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'tan(';
}
}
function addLn() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'ln(';
}
}
h5 {
text-align: right;
color: #333333;
font-family: Arial;
font-size: 12px;
font-weight: bold;
margin: 3px;
}
input[type=text] {
text-align: right;
height: 50px;
width: 176px;
padding: 6px;
border: 10px groove #888888;
background-color: #E5DFA0;
font-family: Luicida, monospace;
}
.scientific {
position: relative;
top:0px;
left: 33px;
}
.scientific input[type=button] {
width: 28px;
height: 28px;
background-color: #444444;
color: #BBBBBB;
font-family: Verdana;
font-size: 8px;
font-weight: bold;
padding: 2px;
margin-top: 2px;
margin-right: 2.5px;
margin-bottom: 0px;
margin-left: 2.5px;
border: none;
}
.scientific input[type=button].cardinal {
width: 28px;
height: 28px;
background-color: red;
color: white;
font-family: Verdana;
font-size: 8px;
font-weight: bold;
padding: 2px;
margin-top: 2px;
margin-right: 2.5px;
margin-bottom: 0px;
margin-left: 2.5px;
border: none;
}
.scientific input[type=image] {
width: 24px;
height: 24px;
background-color: #444444;
padding: 2px;
margin-top: 2px;
margin-right: 2.5px;
margin-bottom: 0px;
margin-left: 2.5px;
border: none;
}
.simple input[type=button] {
width: 32px;
height: 32px;
background-color: #EEEEEE;
color: #222222;
font-family: Verdana;
font-size: 11px;
}
.simple input[type=button].roman {
font-family: "Times New Roman", serif;
font-size: 13px;
}
#calc-contain {
width: 180px;
margin: 0px auto;
}
<html>
<head>
<title>::Scientific Calculator::</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<script type="text/javascript" src="engine.js"></script>
</head><body>
<div id="calc-contain">
<img src="EnData.png" alt="EnData" width="180px" />
<h5>SCIENTIFIC CALCULATOR</h5>
<form id="calculator">
<input type="text" id="screen" value="0" readonly />
<div class="scientific">
<div class="line">
<input type="button" value="RAD" onclick="setAngleMode('rad')" />
<input type="button" value="DEG" onclick="setAngleMode('deg')" />
<input type="button" class="cardinal" value="C" onclick="clearScreen()" />
<input type="button" class="cardinal" value="CE" onclick="clearLast()" />
</div><div class="line">
<input type="button" value="sin" onclick="addSin()" />
<input type="button" value="cos" onclick="addCos()" />
<input type="button" value="tan" onclick="addTan()" />
<input type="button" value="ln" onclick="addLn()" />
</div><div class="line">
<input type="image" src="sqr.png" alt="square" onclick="addSquare()" />
<input type="image" src="nthp.png" alt="nth power" onclick="addPower()" />
<input type="image" src="sqrt.png" alt="square root" onclick="addSquareroot()" />
<input type="image" src="nthr.png" alt="nth root" onclick="addRoot()" />
</div><div class="line">
<input type="button" value="1/x" onclick="inverseVal()" />
<input type="button" value="(" onclick="addSpecial('(')" />
<input type="button" value=")" onclick="addSpecial(')')" />
<input type="button" value="exp" onclick="addExp()" />
</div>
</div>
<div class="simple">
<div class="line">
<input type="button" class="roman" value="π" onclick="addSymbol('pi')" />
<input type="button" value="7" onclick="addSpecial('7')" />
<input type="button" value="8" onclick="addSpecial('8')" />
<input type="button" value="9" onclick="addSpecial('9')" />
<input type="button" value=":" onclick="addSpecial('/')" />
</div><div class="line">
<input type="button" class="roman" value="e" onclick="addSymbol('e')" />
<input type="button" value="4" onclick="addSpecial('4')" />
<input type="button" value="5" onclick="addSpecial('5')" />
<input type="button" value="6" onclick="addSpecial('6')" />
<input type="button" value="x" onclick="addSpecial('*')" />
</div><div class="line">
<input type="button" class="roman" value="φ" onclick="addSymbol('phi')" />
<input type="button" value="1" onclick="addSpecial('1')" />
<input type="button" value="2" onclick="addSpecial('2')" />
<input type="button" value="3" onclick="addSpecial('3')" />
<input type="button" value="-" onclick="addSpecial('-')" />
</div><div class="line">
<input type="button" class="roman" value="γ" onclick="addSymbol('gamma')" />
<input type="button" value="0" onclick="addSpecial('0')" />
<input type="button" value="." onclick="addSpecial('.')" />
<input type="button" value="=" onclick="addSpecial('=')" />
<input type="button" value="+" onclick="addSpecial('+')" />
</div>
</div>
</form>
</div>
</body>
</html>
Any help is appreciated.
I am able to get some functionality, (with some parenthesis errors). If it's not working AT ALL, I suspect you are loading the javascript before the DOM is ready which will cause errors with you getElementById. Try either loading in a window.onload handler or put the script before the closing body tag.
The reset button only appears once a conversion from Fahrenheit to Celsius is successfully done. It works fine. However, after hitting Reset, I cannot see values in the textarea when perform more conversions. I think the problem is most likely caused the two arrays in my codes. What do you think?
I have recreated the problem here: http://jsfiddle.net/wnna3646/
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Temperature Conversion</title>
<style type="text/css">
body { font: 1em calibri, arial; }
button {
background-color: transparent;
margin: 5px;
width: 300px;
}
h1, h2, h3, h4 { text-align: center; }
table {
border: 8px double;
margin-left: auto;
margin-right: auto;
padding: 2px;
height: 500px;
width: 30%;
}
td { border: 1px solid; }
td#topcell {
height: 300px;
text-align: center;
vertical-align: middle;
}
td#midcell {
height: 300px;
text-align: center;
vertical-align: middle;
}
td#bottomcell { text-align: center; }
textarea {
width: 250px;
height: 250px;
}
p {
word-spacing: 25px;
}
#Fahr {
display: inline-block;
float: left;
clear: left;
width: 100px;
text-align: right;
}
#Cels {
display: inline-block;
float: left;
clear: left;
width: 100px;
text-align: right;
}
#ftemp, #ctemp {
display: inline;
float: middle;
}
</style>
</head>
<body>
<main role="main">
<form id="myForm" onsubmit="return this.ftemp.value!=''">
<table>
<tr>
<td id="topcell">
<label for="Fahrenheit" id="Fahr">Fahrenheit:</label><input id="ftemp" onkeypress="return fNumericCharactersOnly(event)" onkeyup="this.form.Convertbtn.disabled = this.value==''; this.form.Avgbtn.disabled = this.value==''; if(!validnum(this.value)) this.value=''">
<br /><br />
<label for="Celsius" id="Cels" >Celsius:</label><input id="ctemp" readonly>
<br /><br /><br /><br /><br /><br />
<p>Fahrenheit Celsius</p>
</td>
</tr>
<tr>
<td id="midcell">
<br />
<textarea rows="5" id="txtArea" readonly></textarea>
</td>
</tr>
<tr>
<td id="bottomcell">
<input type="button" id="Convertbtn" value="Convert" accesskey="c" onclick="convertTemp(); counter++" disabled="disabled"/>
<input type="button" id="Avgbtn" value="Average" accesskey="a" onclick="averageTemp(); AddResetbutton()" disabled="disabled"/>
<div id="ButtonSpot"></div>
</td>
</tr>
</table>
</form>
</main>
<script type="text/javascript">
var flist = [];
var clist = [];
var counter = 0;
function validnum(F) {
if(F < -9999 || F > 9999)
return false;
else
return true;
}
function fNumericCharactersOnly(evt){
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
return (charCode >= 48 && charCode <= 57); // 48 to 57 ==> 0 to 9
}
function convertTemp() {
var c = document.getElementById('ctemp'),
f = document.getElementById('ftemp');
c.value = parseFloat(Math.round((f.value - 32) * 5 / 9)).toFixed(2);
tf = f.value, tc = c.value;
flist.push(tf); clist.push(tc);
var str = "";
str += '\t' + tf + '\t' + ' ' + ' ' + tc + "\n";
document.getElementById("txtArea").innerHTML = str;
}
function averageTemp() {
var content="";
var sumF = 0;
var sumC = 0;
for (var i = 0; i < flist.length; i++) {
content += '\t' + flist[i] + '\t' + ' ' + ' ' + clist[i] + "\n";
sumF += parseInt(flist[i], 10);
sumC += parseInt(clist[i], 10);
}
bars = '===============================';
var avgF = parseFloat(sumF / flist.length).toFixed(2);
var avgC = parseFloat(sumC / clist.length).toFixed(2);
document.getElementById("txtArea").innerHTML = content + bars + "\n" + '\t' + avgF + '\t' + ' ' + ' ' + avgC;
flist = [];
clist = [];
document.getElementById("Avgbtn").disabled=true;
}
function AddResetbutton() {
document.getElementById('ButtonSpot').innerHTML = '<input type="button" onClick="removeButton();" value="Reset" />';
document.getElementById("Convertbtn").disabled=true;
}
function removeButton() {
document.getElementById("myForm").reset();
document.getElementById('ButtonSpot').innerHTML = '';
document.getElementById("txtArea").value = "";
document.getElementById("Convertbtn").disabled=true;
document.getElementById("Avgbtn").disabled=true;
}
</script>
</body>
</html>
Also, I have attempted to make the script automatically display all values after the 10th one is entered, but can't seem to make it work. Any suggestions?
Hey Your code is fixed.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Temperature Conversion</title>
<style type="text/css">
body { font: 1em calibri, arial; }
button {
background-color: transparent;
margin: 5px;
width: 300px;
}
h1, h2, h3, h4 { text-align: center; }
table {
border: 8px double;
margin-left: auto;
margin-right: auto;
padding: 2px;
height: 500px;
width: 30%;
}
td { border: 1px solid; }
td#topcell {
height: 300px;
text-align: center;
vertical-align: middle;
}
td#midcell {
height: 300px;
text-align: center;
vertical-align: middle;
}
td#bottomcell { text-align: center; }
textarea {
width: 250px;
height: 250px;
}
p {
word-spacing: 25px;
}
#Fahr {
display: inline-block;
float: left;
clear: left;
width: 100px;
text-align: right;
}
#Cels {
display: inline-block;
float: left;
clear: left;
width: 100px;
text-align: right;
}
#ftemp, #ctemp {
display: inline;
float: middle;
}
</style>
</head>
<body>
<main role="main">
<form id="myForm" onsubmit="return this.ftemp.value!=''">
<table>
<tr>
<td id="topcell">
<label for="Fahrenheit" id="Fahr">Fahrenheit:</label><input id="ftemp" onkeypress="return fNumericCharactersOnly(event)" onkeyup="this.form.Convertbtn.disabled = this.value==''; this.form.Avgbtn.disabled = this.value==''; if(!validnum(this.value)) this.value=''">
<br /><br />
<label for="Celsius" id="Cels" >Celsius:</label><input id="ctemp" readonly>
<br /><br /><br /><br /><br /><br />
<p>Fahrenheit Celsius</p>
</td>
</tr>
<tr>
<td id="midcell">
<br />
<textarea rows="5" id="txtArea" name="textarea-name" readonly></textarea>
</td>
</tr>
<tr>
<td id="bottomcell">
<input type="button" id="Convertbtn" value="Convert" accesskey="c" onclick="convertTemp(); counter++" disabled="disabled"/>
<input type="button" id="Avgbtn" value="Average" accesskey="a" onclick="averageTemp(); AddResetbutton()" disabled="disabled"/>
<div id="ButtonSpot"></div>
</td>
</tr>
</table>
</form>
</main>
<script type="text/javascript">
var flist = [];
var clist = [];
var counter = 0;
function validnum(F) {
if(F < -9999 || F > 9999)
return false;
else
return true;
}
function fNumericCharactersOnly(evt){
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
return (charCode >= 48 && charCode <= 57); // 48 to 57 ==> 0 to 9
}
function convertTemp() {
var c = document.getElementById('ctemp'),
f = document.getElementById('ftemp');
c.value = parseFloat(Math.round((f.value - 32) * 5 / 9)).toFixed(2);
tf = f.value, tc = c.value;
flist.push(tf); clist.push(tc);
var str = "";
str += '\t' + tf + '\t' + ' ' + ' ' + tc + "\n";
document.getElementById("txtArea").innerHTML = str;
}
function averageTemp() {
var content="";
var sumF = 0;
var sumC = 0;
for (var i = 0; i < flist.length; i++) {
content += '\t' + flist[i] + '\t' + ' ' + ' ' + clist[i] + "\n";
sumF += parseInt(flist[i], 10);
sumC += parseInt(clist[i], 10);
}
bars = '===============================';
var avgF = parseFloat(sumF / flist.length).toFixed(2);
var avgC = parseFloat(sumC / clist.length).toFixed(2);
document.getElementById("txtArea").innerHTML = content + bars + "\n" + '\t' + avgF + '\t' + ' ' + ' ' + avgC;
flist = [];
clist = [];
document.getElementById("Avgbtn").disabled=true;
}
function AddResetbutton() {
document.getElementById('ButtonSpot').innerHTML = '<input type="button" onClick="removeButton();" value="Reset" />';
document.getElementById("Convertbtn").disabled=true;
}
function removeButton() {
document.getElementById("myForm").reset();
document.getElementById('ButtonSpot').innerHTML = '';
document.getElementById("txtArea").innerHTML = '';
document.getElementById("Convertbtn").disabled=true;
document.getElementById("Avgbtn").disabled=true;
}
</script>
</body>
</html>
I can't find a good calculator in JavaScript.
In a first time I was using the eval function on my datas to get my result but there were mistakes.
So I found this code:
function calculate(input){
var f = { add : '+'
, sub : '-'
, div : '/'
, mlt : '*'
, mod : '%'
, exp : '^' };
// Create array for Order of Operation and precedence
f.ooo = [[ [f.mlt] , [f.div] , [f.mod] , [f.exp] ],
[ [f.add] , [f.sub] ]];
input = input.replace(/[^0-9%^*\/()\-+.]/g,''); // clean up unnecessary characters
var output;
for(var i=0, n=f.ooo.length; i<n; i++ ){
// Regular Expression to look for operators between floating numbers or integers
var re = new RegExp('(\\d+\\.?\\d*)([\\'+f.ooo[i].join('\\')+'])(\\d+\\.?\\d*)');
re.lastIndex = 0; // be cautious and reset re start pos
// Loop while there is still calculation for level of precedence
while( re.test(input) ){
//document.write('<div>' + input + '</div>');
output = calc_internal(RegExp.$1,RegExp.$2,RegExp.$3);
if (isNaN(output) || !isFinite(output)) return output; // exit early if not a number
input = input.replace(re,output);
}
}
return output;
function calc_internal(a,op,b){
a=a*1; b=b*1;
switch(op){
case f.add: return a+b; break;
case f.sub: return a-b; break;
case f.div: return a/b; break;
case f.mlt: return a*b; break;
case f.mod: return a%b; break;
case f.exp: return Math.pow(a,b); break;
default: null;
}
}
}
http://jsfiddle.net/vol7ron/6cdfA/
But there are some problems using parenthesis, for example: (10+1)*5 = 11
So I'm trying to find a good calculator in JavaScript to calculate string expressions.
Thanks for your help.
You can use the math.js library, which comes with a powerful expression parser:
http://mathjs.org
I don't have javascript code for it, but general solution how to evaluate complex expresion in string is to convert it using Shunting-yard algorithm into RPN and then use Reverse Polish notation algorithm to get result.
This is a solution i recently come up with as an exercise for using clusure in Javascript.
var PocketCalculator = function() {
var allowedOperators = ["+", "-", "*", "/", "="],
operations = {
"+": function(a, b) {
return a + b;
},
"-": function(a, b) {
return a - b;
},
"*": function(a, b) {
return a * b;
},
"/": function(a, b) {
return a / b;
}
},
cache = 0,
makeOperation = function(b, f) {
return function() {
return cache = f(cache, b);
};
},
prevOperation = operations["+"],
operation = makeOperation(0, prevOperation);
return {
clear: function() {
cache = 0;
prevOperation = operations["+"]
operation = makeOperation(0, prevOperation);
},
push: function(operator, b) {
if (allowedOperators.indexOf(operator) < 0)
return;
if (operator !== "=") {
prevOperation = operations[operator];
operation = makeOperation(b, prevOperation);
} else if (b !== undefined)
operation = makeOperation(b, prevOperation);
return operation();
}
};
};
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
::selection { background-color: #E13300; color: white; }
::-moz-selection { background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#body {
margin: 0 15px 0 15px;
}
p.footer {
text-align: right;
font-size: 11px;
border-top: 1px solid #D0D0D0;
line-height: 32px;
padding: 0 10px 0 10px;
margin: 20px 0 0 0;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
box-shadow: 0 0 8px #D0D0D0;
}
</style>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".num").click(function(){
var oprator = $("#val2").val();
var one = $(this).val();
if (oprator=='') {
var val1 = $("#val1").val();
$("#val1").val(val1+one);
}else{
var val1 = $("#val3").val();
$("#val3").val(val1+one);
}
});
$(".opt").click(function(){
var plus = $(this).val();
$("#val2").val(plus);
});
$("#equle").click(function(){
var plus = $("#equle").val();
var v1 = $("#val1").val();
var v2 = $("#val2").val();
var v3 = $("#val3").val();
var v1int=parseInt(v1);
var v3int=parseInt(v3);
if (v2=="+") {
var z = v1int+v3int;
}else if(v2=="-"){
var z = v1int-v3int;
}
else if(v2=="*"){
var z = v1int*v3int;
}
else{
var z = v1int/v3int;
}
$("#val4").val(z);
});
});
</script
<body>
<div id="container">
<h1>Welcome to CodeIgniter!</h1>
<div id="body">
<table>
<tr cospan="5">
<td colspan="2"><input type='text' name="val1" value="" id="val1"/></td>
<td colspan="1"><input type='text' name="val2" value="" id="val2"/></td>
<td colspan="1"><input type='text' name="val3" value="" id="val3"/></td>
<td colspan="1"><input type='text' name="val4" value="" id="val4"/></td></tr>
<tr>
<td><button type="button" class="num" id="one" value="1">1</button></td>
<td><button type="button" class="num" id="two" value="2">2</button></td>
<td><button type="button" class="num" id="three" value="3">3</button></td>
<td><button type="button" class="num" id="four" value="4">4</button</td>
<td><button type="button" class="num" id="five" value="5">5</button></td>
</tr>
<tr>
<td><button type="button" class="num" id="six" value="6">6</button></td>
<td><button type="button" class="num" id="seven" value="7">7</button></td>
<td><button type="button" class="num" id="eight" value="8">8</button></td>
<td><button type="button" class="num" id="nine" value="9">9</button></td>
<td><button type="button" class="num" id="ten" value="10">0</button></td>
</tr>
<tr>
<td><button type="button" id="plus" class="opt" value="+">+</button></td>
<td><button type="button" id="minus" class="opt" value="-">-</button></td>
<td><button type="button" id="mul" class="opt" value="*">*</button></td>
<td><button type="button" id="dev" class="opt" value="/">/</button></td>
<td><button type="button" id="equle" value="=">=</button></td>
</tr>
</table>
</div>
</div>
</body>
</html>