Use conditional statement to write a JavaScript calculator - javascript

I'm new to JavaScript. I did a simple calculator that has 2 inputs values with 4 buttons of operators. How can I fix this JavaScript so that it can count the numbers based on different operators and display the correct output? How to write it using if else condition or switch cases?
Now I have pressed every button it only shows the output with sum only.
function count() {
var n1 = parseFloat(document.getElementById("num1").value);
var n2 = parseFloat(document.getElementById("num2").value);
var optr = document.getElementById("operator").value;
let result;
if (optr == '+') {
result = n1 + n2;
} else if (optr == '-') {
result = n1 - n2;
} else if (optr == '*') {
result = n1 * n2;
} else {
result = n1 / n2;
}
document.getElementById("output").innerHTML = "Total is: " + result;
}
Number 1:<input type="number" id="num1"><br><br> Number 2:<input type="number" id="num2"><br><br>
<input type="button" value="+" onclick="count()" id="operator">
<input type="button" value="-" onclick="count()" id="operator">
<input type="button" value="*" onclick="count()" id="operator">
<input type="button" value="/" onclick="count()" id="operator">
<p id="output"></p>

There are many ways to achieve what you want. Here is one that I have prepared by modifying/simplifying your original code:
const in1 = document.getElementById("num1"),
in2 = document.getElementById("num2");
document.addEventListener("click", function(ev) {
if (ev.target.classList.contains("operator")) {
let optr = ev.target.value,
n1 = +in1.value,
n2 = +in2.value,
result;
if (optr == '+') result = n1 + n2;
else if (optr == '-') result = n1 - n2;
else if (optr == '*') result = n1 * n2;
else result = n1 / n2;
document.getElementById("output").innerHTML = "Total is: " + result;
}
})
Number 1:<input type="number" id="num1"><br><br> Number 2:<input type="number" id="num2"><br><br>
<input type="button" value="+" class="operator">
<input type="button" value="-" class="operator">
<input type="button" value="*" class="operator">
<input type="button" value="/" class="operator">
<p id="output"></p>
A few remarks:
id attributes must always be unique on a page. I replaced the ids in your buttons by class attributes.
the values of your input elements must be evaluated at the time the operator button is clicked.
the conversion from text to numerical values is done implicitly by applying the unary + operator in front of in1.value and in2.value.
instead of assigning the handler function through the html-onclick attribute I used a delegated event attachment: the click event is attached to the whole document but will only cause an action if the actual clicked element (ev.target) has the word "operator" in its class list.

Switch case or If/else. Both is right. But I prefer the switch case version, because it is cleaner. Following #CarstenMassmann's answer, here is the switch case path:
const in1 = document.getElementById("num1");
const in2 = document.getElementById("num2");
document.addEventListener("click", function(e) {
if (e.target.classList.contains("operator")) {
const optr = e.target.value
const n1 =+ in1.value;
const n2 =+ in2.value;
let result = 'i dont know';
switch (optr) {
case '+':
result = n1 + n2
break;
case '-':
result = n1 - n2
break;
case '*':
result = n1 * n2;
break;
case '/':
result = n1 / n2;
}
document.getElementById("output").innerHTML = "= " + result;
}
})
Number 1:<input type="number" id="num1"><br><br> Number 2:<input type="number" id="num2"><br><br>
<input type="button" value="+" class="operator">
<input type="button" value="-" class="operator">
<input type="button" value="*" class="operator">
<input type="button" value="/" class="operator">
<p id="output"></p>

Related

Adding two numbers in javascript from two inputs in a form

I am new in JavaScript. As a result I was practicing some codes that reads two numbers from a form and display the result on a button click. I also want to add a reset button to start a new calculation. The problem is the result field is not updating on button click but the reset button is working. Below is my code:
const btn = document.getElementById('btn');
const calc = document.getElementById('calc');
function add() {
const num1 = parseInt(document.getElementById('num1').value);
const num2 = parseInt(document.getElementById('num2').value);
const result = document.getElementById('result');
if (num1 && num2 !== NaN) {
calc.addEventListener('click', () => {
let sum = num1 + num2;
result.value = sum;
return false;
});
} else {
alert("Enter Valid Number");
}
}
btn.addEventListener('click', () => {
num1.value = " ";
num2.value = " ";
result.value = " ";
});
<form id="adder" onsubmit="return add();">
<input type="text" name="num1" id='num1' placeholder="enter number">
<input type="text" name="num2" id='num2' placeholder="enter number">
<button id="calc" type="button">Add</button>
<input type="text" name="num3" id="result" readonly placeholder="Result">
<button type="button" id="btn">Clear</button>
</form>
You need to create addEventListener of calc button outside add(); and call add(); into event;
const btn = document.getElementById('btn');
const calc = document.getElementById('calc');
function add() {
const num1 = parseInt(document.getElementById('num1').value);
const num2 = parseInt(document.getElementById('num2').value);
const result = document.getElementById('result');
if (num1 && num2 !== NaN) {
let sum = num1 + num2;
result.value = sum;
return false;
} else {
alert("Enter Valid Number");
}
}
calc.addEventListener('click', () => {
add();
});
btn.addEventListener('click', () => {
num1.value = " ";
num2.value = " ";
result.value = " ";
});
<form id="adder" onsubmit="return add();">
<input type="text" name="num1" id='num1' placeholder="enter number">
<input type="text" name="num2" id='num2' placeholder="enter number">
<button id="calc" type="button">Add</button>
<input type="text" name="num3" id="result" readonly placeholder="Result">
<button type="button" id="btn">Clear</button>
</form>
onsubmit doesn't fire because you didn't add a submit button, anyway that method doesn't work because you add an eventListener that will work after press submit.

How do I make these functions shorter

I was making a simple calculator with two input boxes for each number, and four buttons for each operation underneath. After pressing one of the buttons (Ex:Add) They would perform the operation. However, inside each function I had to keep writing these two lines:
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
Is there a way I could write these before I make each individual function? Could someone with more skill possibly show me what I could do?
function add() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 + Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function sub() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 - Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function mul() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 * Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function div() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 / Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="add()">Add</button>
<button type="button" onclick="sub()">Subtract</button>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
Is there a way I could write these before I make each individual function?
You can get the elements just once:
const input1 = document.getElementById("Value1");
Then when you need its value:
const value1 = input1.valueAsNumber;
In general, you can usually write a function to avoid duplicated logic. Probably not appropriate in this case, but for example:
function getValueAsNumber(id) {
return document.getElementById(id).valueAsNumber;
}
then
const value1 = getValueAsNumber("Value1");
A couple of side notes:
In JavaScript and related languages, the overwhelming convention is to use an initial lower case letter for variables that don't refer to constructor functions. So value1 rather than Value1, value1Element rather than Value1Element, etc.
var is no longer best practice in JavaScript. In new code, prefer let or const because of their more useful scoping.
When putting just plain text in an element, you're better off using textContent rather than innerHTML, because the browser doesn't try to parse the text you give it as HTML.
onxyz-attribute-style event handlers are not best practice, not least because the functions they call have to be globals, and the global namespace is crowded. Consider using modern event handling (addEventListener and the like).
Just for an example, here's your code with some of the above applied, but without going overboard:
const gid = id => document.getElementById(id);
const input1 = gid("Value1");
const input2 = gid("Value2");
const demo = gid("demo");
gid("add").addEventListener("click", () => {
const total = input1.valueAsNumber + input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
gid("sub").addEventListener("click", () => {
const total = input1.valueAsNumber - input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
gid("mul").addEventListener("click", () => {
const total = input1.valueAsNumber * input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
gid("div").addEventListener("click", () => {
const total = input1.valueAsNumber / input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" id="add">Add</button>
<button type="button" id="sub">Subtract</button>
<button type="button" id="mul">Multiply</button>
<button type="button" id="div">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
Or we could abstract away everything but the operation itself (just for fun):
const gid = id => document.getElementById(id);
const input1 = gid("Value1");
const input2 = gid("Value2");
const demo = gid("demo");
const clickHandler = (id, operation) => {
// ^^^^^^^^^
gid(id).addEventListener("click", () => {
const total = operation(input1.valueAsNumber, input2.valueAsNumber);
// ^^^^^^^^^
demo.textContent = "Total: " + total;
});
};
clickHandler("add", (a, b) => a + b);
// ^^^^^^^^^^^^^^^
clickHandler("sub", (a, b) => a - b);
clickHandler("mul", (a, b) => a * b);
clickHandler("div", (a, b) => a / b);
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" id="add">Add</button>
<button type="button" id="sub">Subtract</button>
<button type="button" id="mul">Multiply</button>
<button type="button" id="div">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
You could even go further than that, but it starts getting hard to follow. :-)
You can make a function to get the value of an element by ID, and re-use it, also you can create 1 function that will show the total as well.
function showTotal(total) {
document.getElementById('demo').innerHTML = "Total: " + total;
}
function getValue(id) {
return document.getElementById(id).valueAsNumber;
}
function add() {
showTotal(getValue("Value1") + getValue("Value2"));
}
function sub() {
showTotal(getValue("Value1") - getValue("Value2"));
}
function mul() {
showTotal(getValue("Value1") * getValue("Value2"));
}
function div() {
showTotal(getValue("Value1") / getValue("Value2"));
}
<body style="text-align:center"><br><br>
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="add()">Add</button>
<button type="button" onclick="sub()">Subtract</button>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
</body>
Some suggestions:
Let's separate the calculating from the formatted displaying. We'll have one function to calculate (+, -, /, *) and a different function to handle innerHTML-setting.
Since the calculations are all in one function, that removes the redundancy of multiple document.getElementById calls throughout your code.
We can use a switch() statement to determine the operation to apply, although a standard if()/else() also would work.
Working demo...
function operate(e) {
var Total = getOperationTotal(e);
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function getOperationTotal(e) {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var total;
switch(e.target.id) {
case 'add-button':
total = Value1 + Value2;
break;
case 'subtract-button':
total = Value1 - Value2;
break;
case 'multiply-button':
total = Value1 * Value2;
break;
case 'divide-button':
total = Value1 / Value2;
break;
}
return total;
}
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button id="add-button" type="button" onclick="operate(event)">Add</button>
<button id="subtract-button" type="button" onclick="operate(event)">Subtract</button>
<button id="multiply-button" type="button" onclick="operate(event)">Multiply</button>
<button id="divide-button" type="button" onclick="operate(event)">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
You can define global variables and additionally add onchange functions for the input, so as soon as you change the number the value changes in JS too.
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
function updateNr(id){
(id === 1) ? Value1 = document.getElementById('Value1').valueAsNumber : Value2 = document.getElementById('Value2').valueAsNumber;
}
function add() {
var Total = Value1 + Value2;
postAnswer(Total);
}
function sub() {
var Total = Value1 - Value2;
postAnswer(Total);
}
function mul() {
var Total = Value1 * Value2;
postAnswer(Total);
}
function div() {
var Total = Value1 / Value2;
postAnswer(Total);
}
function postAnswer(total){
document.getElementById('demo').innerHTML = "Total: " + total;
}
First Number: <input onchange="updateNr(1)" type="number" id="Value1"><br><br>
Second Number: <input onchange="updateNr(2)" type="number" id="Value2"><br><br>
<button type="button" onclick="add()">Add</button>
<button type="button" onclick="sub()">Subtract</button>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
<body style="text-align:center"><br><br>
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="action(this)">Add</button>
<button type="button" onclick="action(this)">Subtract</button>
<button type="button" onclick="action(this)">Multiply</button>
<button type="button" onclick="action(this)">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
<script>
action = (e) => {
const Value1 = document.getElementById('Value1').valueAsNumber;
const Value2 = document.getElementById('Value2').valueAsNumber;
let Total = null;
switch(e.textContent) {
case 'Add':
Total = Value1 + Value2;
break;
case 'Subtract':
Total = Value1 - Value2;
break;
case 'Multiply':
Total = Value1 * Value2;
break;
case 'Divide':
Total = Value1 / Value2;
break;
}
document.getElementById('demo').innerHTML = `Total: ${Total}`;
}
</script>
</body>
We dont need to write each function for each calculation, Try to reuse the code insted of re-writing it, Since you are trying to execute the same logic but only the arithmetic operators are changed in each function you defined, we can write a single function and change the operators depending on the calculations we intend to perform. Below code uses function calculate(operation) which takes operation as a parameter and gives us the result depending on the argument passed.
Always try to use let insted of var as let has block scope but var doesn't
Also for better code readability and consistency follow naming conventions to name your variables
function calculate(operation){
let total;
let value1 = document.getElementById('Value1').valueAsNumber;
let value2 = document.getElementById('Value2').valueAsNumber;
if(operation == 'add') total = value1 + value2;
else if(operation == 'sub') total = value1 - value2;
else if(operation == 'multiply') total = value1 * value2;
else if(operation == 'devide') total = value1 / value2;
document.getElementById('demo').innerHTML = "Total: " + total;
}
<body style="text-align:center"><br><br>
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="calculate('add')">Add</button>
<button type="button" onclick="calculate('sub')">Subtract</button>
<button type="button" onclick="calculate('multiply')">Multiply</button>
<button type="button" onclick="calculate('devide')">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
</body>

Should I be using else-if statements for these?

I'm very new to coding, and have been trying to create a very simple calculator using HTML and JavaScript where the user inputs two values, selects an operator from a selection of buttons, and then gets a result.
I'd appreciate some guidance from people who know what they're doing!!
I've tried implementing else-ifs, but it doesn't appear to be solving the issue. Only the last line of the function is executing. Python wasn't this hard?!
<button id="a" value="+">+</button>
<button id="b" value="-">-</button>
<button id="c" value="/">/</button>
<button id="d" value="X">X</button>
<input type="text" id="n1"/>
<input type="text" id="n2"/>
<script>
function calc()
{
var n1 = parseFloat(document.getElementById('n1').value);
var n2 = parseFloat(document.getElementById('n2').value);
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var d = document.getElementById("d").value;
if(a === '+')
{
document.getElementById('result').value = n1+n2;
}
if(b === '-')
{
document.getElementById('result').value = n1-n2;
}
if(c === '/')
{
document.getElementById('result').value = n1/n2;
}
if(d === 'X')
{
document.getElementById('result').value = n1*n2;
}
}
</script>
I'm expecting each line to be executed to produce the correct operand, but at present the only last line (n1*n2) is giving me anything.
All your conditions are true, since the value of a button doesn't change depending on whether the user clicked on it.
You should change calc() so it takes the button as a parameter, then checks the value of the parameter's value. A switch statement is an easy way to write this type of check.
function calc(button) {
var n1 = parseFloat(document.getElementById('n1').value);
var n2 = parseFloat(document.getElementById('n2').value);
let result;
switch (button.value) {
case '+':
result = n1 + n2;
break;
case '-':
result = n1 - n2;
break;
case '/':
result = n1 / n2;
break;
case 'X':
result = n1 * n2;
break;
}
document.getElementById('result').value = result;
}
<input type="text" id="n1" />
<input type="text" id="n2" /><br>
<button id="a" value="+" onclick="calc(this)">+</button>
<button id="b" value="-" onclick="calc(this)">-</button>
<button id="c" value="/" onclick="calc(this)">/</button>
<button id="d" value="X" onclick="calc(this)">X</button>
<br>
<input type="text" id="result" readonly />

Why it gives me String every time?

I got input from input tags but whatever I write in inputs it recognize as string value so that I can't use my conditions.
and the second problem if I enter "ddd" for first input and "111" for second input and press button it shows NaN in console. I want to show alert instead of this. How can I correct these?
function addFunc() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
if (typeof x == 'string' || typeof y == 'string') {
var result = parseInt(x) + parseInt(y);
console.log(result);
} else {
alert("Wrong Entry!");
}
}
<input id="num1">
<input id="num2">
<button type="button" onclick="addFunc()">ADD</button>
<p id="result"></p>
The value of an input field will always be a string. Try using isNaN() to determine if the decimal parsed correctly:
function addFunc() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
if ( !isNaN(x) && !isNaN(y) )
{
var result = x + y;
console.log(result);
}
else {
alert("Wrong Entry!");
}
}
<form onsubmit="addFunc(); return false">
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" value="Add" />
</form>
Alternatively, if you want to eliminate all bad input (1e would be invalid), try using a + symbol before the string value to convert it to a number. If the string can't be converted, it will return NaN:
function addFunc() {
var x = +document.getElementById("num1").value;
var y = +document.getElementById("num2").value;
if ( !isNaN(x) && !isNaN(y) )
{
var result = x + y;
console.log(result);
}
else {
alert("Wrong Entry!");
}
}
<form onsubmit="addFunc(); return false">
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" value="Add" />
</form>

Javascript Text Input Calculator

I am somewhat new to Javascript and I'm trying to make a basic calculator that has 3 text inputs, a 1st number text box, an operation textbox, and a second number textbox, but it doesn't print out the text when I click a button or use any other method to trigger the event.
This is my code:
<html>
<script>
function calc()
{
var D = "";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if(B == "+")
{
D = A+C;
}
elseif(B == "-")
{
D = A-C;
}
elseif(B == "*")
{
D = A*C;
}
elseif(B == "/")
{
D = A/C;
}
document.getElementById("result").innerHTML = D;
}
</script>
<body>
<input type="text" id="num1" name="num1" />
<input type="text" id="op" name="op" />
<input type="text" id="num2" name="num2" />
<br />
<input type="button" value="Solve" onclick="calc()" />
<p id="result" name="r1">
<br />
</p>
</body>
</html>
I'd suggest the following (explanations commented in the code itself):
function calc() {
/* finds out whether the browser uses textContent (Webkit, Opera, Mozilla...)
or innerText (Microsoft) to set the text of an element/node */
var textType = Node.textContent ? 'textContent' : 'innerText',
/* uses parseFloat to create numbers (where possible) from the entered value
if parseFloat fails to find a number (it's empty or nonsensical)
then a 0 is used instead (to prevent NaN being the output). */
num1 = parseFloat(document.getElementById('num1').value) || 0,
num2 = parseFloat(document.getElementById('num2').value) || 0,
// retrieves the result element
result = document.getElementById('result');
// switch is used to avoid lots of 'if'/'else if' statements,
// .replace() is used to remove leading, and trailing, whitespace
// could use .trim() instead, but that'd need a shim for (older?) IE
switch (document.getElementById('op').value.replace(/\s/g,'')){
// if the entered value is:
// a '+' then we set the result element's text to the sum
case '+':
result[textType] = num1 + num2;
break;
// and so on...
case '-':
result[textType] = num1 - num2;
break;
case '*':
result[textType] = num1 * num2;
break;
case '/':
result[textType] = num1 / num2;
break;
// because people are going to try, give a default message if a non-math
// operand is used
default:
result[textType] = 'Seriously? You wanted to try math with that operand? Now stop being silly.'
break;
}
}
JS Fiddle demo.
References:
parseFloat().
switch () {...}.
I would have done things a bit differently, but to answer your question and just get your code working I did the following:
Here is your reworked code:
<html>
<script>
function calc(form) {
var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if (B === "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B === "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B === "*")
{
D = parseInt(A)*parseInt(C);
}
else if (B === "/")
{
D = parseInt(A)/parseInt(C);
}
document.getElementById("result").innerHTML = D;
return false;
}
</script>
<body>
<input type="text" id="num1" name="num1" />
<input type="text" id="op" name="op" />
<input type="text" id="num2" name="num2" />
<br />
<input type="button" value="Solve" onClick="calc(this)">
<p id="result" name="r1">
<br />
</p>
</body>
</html>
I used the parseint() because your expressions in your if statements were treating values like text.
Next we need to use === Three equals which says A is really equal to + or what ever the second input value is.
Third was the onclick, I did a (this) and feed back form as you can see in the line that says function calc.
For good measure I added a return false; to prevent form submission (but it will function without it).
Also like other posters stated it is else if and not elseif.
I hope this is helpful. Again, I would do things differently but got it working with some explanations.
I recommend using eval()
If the user inputs "5+6" or "(9*3)/5" and you set that to a variable, eval() will parse and solve the problem!
It's else if not elseif. Also you need to use parseInt on A+C, otherwise it will treat your strings as...well, strings. You should have seen the elseif error in your browser. Are you using something like firebug? If you aren't, start. Let tools do the hard work for you.
There is a way you can do it with a single input box:
function findOps(s) {
for (var i = 0; i < s.length; i++) {
if (s[i] == "+")
return "+";
if (s[i] == "-")
return "-";
if (s[i] == "*")
return "*";
if (s[i] == "/")
return "/";
}
}
var input = '';
function calc() {
var dom = $("#input");
input = dom.val();
try {
switch (findOps(input)) {
case "+":
var a = input.split("+");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x + y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
case "-":
var a = input.split("-");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x - y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
case "*":
var a = input.split("*");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x * y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
case "/":
var a = input.split("/");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x / y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
}
} catch (err) {
alert("catched¡");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Amanpreet singh</title>
</head>
<body>
<center>
<table cellpadding="10" cellspacing="10" style="font-size:2em">
<tr><td>Number 1:</td>
<td><input type="text" id="num1" name="num1" /></td>
</tr>
<tr><td>Number 2:</td>
<td> <input type="text" id="num2" name="num2" /></td>
</tr>
<tr>
<td> <label for=" Operator"> Operator:</label></td>
<td> <select name="Operator" id="op" name="op">
<option value="+">Add</option> <option value="-">Subtract</option>
<option value="*">Muliply</option><option value="/">Divide</option>
</select></td>
</tr>
<tr><td colspan="2" align="cover">
<center> <input type="button" value="Solve" onclick="calc()" />
</center></td>
</tr>
<tr><td colspan="2" style="text-align: center;"><p id="result" name="r1" ></p></td></tr>
</table></center>
<script type="text/javascript">
function calc() {
var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if (B === "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B === "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B === "*")
{
D = parseInt(A)*parseInt(C);
}
else if (B === "/")
{
D = parseInt(A)/parseInt(C);
}
document.getElementById("result").innerHTML = "Result is :"+D;
return false;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Amanpreet singh</title>
</head>
<body>
<center>
<table cellpadding="10" cellspacing="10" style="font-size:2em">
<tr><td>Number 1:</td>
<td><input type="text" id="num1" name="num1" /></td>
</tr>
<tr><td>Number 2:</td>
<td> <input type="text" id="num2" name="num2" /></td>
</tr>
<tr>
<td> <label for=" Operator"> Operator:</label></td>
<td> <select name="Operator" id="op" name="op">
<option value="+">Add</option> <option value="-">Subtract</option>
<option value="*">Muliply</option><option value="/">Divide</option>
</select></td>
</tr>
<tr><td colspan="2" align="cover">
<center> <input type="button" value="Solve" onclick="calc()" />
</center></td>
</tr>
<tr><td colspan="2" style="text-align: center;"><p id="result" name="r1" ></p></td></tr>
</table></center>
<script type="text/javascript">
function calc() {
var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if (B === "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B === "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B === "*")
{
D = parseInt(A)*parseInt(C);
}
else if (B === "/")
{
D = parseInt(A)/parseInt(C);
}
document.getElementById("result").innerHTML = "Result is :"+D;
return false;
}
</script>
</body>
</html>

Categories

Resources