Should I be using else-if statements for these? - javascript

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 />

Related

Use conditional statement to write a JavaScript calculator

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>

JavaScript calculator not updating values

I have a problem with my JavaScript calculator. Whenever I want to add, for example, 5+5, the result stays at 10 (blocked on one value) and does not add to the previous result (10, 15, 20, etc.).
Here is my code:
function add() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a + b);
document.getElementById('result').value = +c;
}
function sub() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a - b);
document.getElementById('result').value = +c;
}
function mult() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a * b);
document.getElementById('result').value = +c;
}
function div() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a / b);
document.getElementById('result').value = +c;
}
function divmod() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a % b);
document.getElementById('result').value = +c;
}
<form name="calculator">
<input type="text" id="l1" />
<input type="text" id="l2" />
<br/>
<input type="button" value="+" onclick="add()" />
<br/>
<input type="button" value="-" onclick="sub()" />
<br/>
<input type="button" onclick="mult()" />
<br/>
<input type="button" value="%" onclick="divmod()" />
<input type="button" value="/" onclick="div()" />
<br/>
<input type="button" value="clean" class="class2" />
<br/>
<p style="color:white; font-size:30px;">Result:</p>
<input type="text" id="result" />
<br/>
</form>
Where is the problem? I tried add + before = in document.getElementById('result').value = +c but it did not update the value then, but added 5 + 5 as 55.
While the +c is on the right track (converting c to a number), c is already a number, it is the result of parseInt(). The reason you got 55 is because it was concatenating strings, not adding numbers (JS can be funky with the string to number thing because it is not a strongly typed language). Javascript's type coercion can be a big pain sometimes!
I believe that getting the value of result, casting it to an integer, adding c to that integer, and THEN setting the DOM element value will get you the behavior you are looking for.
I am being intentionally vague because I believe you have demonstrated that you have the knowledge and tools to do this from your code sampling above. If you still can't get it to work after more effort, please comment on this answer and I will provide a more in depth solution.
You need to add to the number by first parsing the value to an int:
document.getElementById('result').value = parseInt(document.getElementById('result').value) + c;
With just a = newValue, that is changing the value of result to be the c variable .
With just a += newValue, that is concatenation since document.thing.value will always return a string, and a string + number promotes the number to a string.
So you need to say oldStringValue = parseInt(oldStringValue) + newNumberValue;
The value of result also needs to be initialized to 0, either through the HTML or JavaScript, otherwise parseInt() will return NaN. I chose to do it in the JavaScript, as that's more clear.
document.getElementById('result').value = 0;
function add() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a + b);
document.getElementById('result').value = parseInt(document.getElementById('result').value) + c;
}
function sub() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a - b);
document.getElementById('result').value = parseInt(document.getElementById('result').value) + c;
}
function mult() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a * b);
document.getElementById('result').value = parseInt(document.getElementById('result').value) + c;
}
function div() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a / b);
document.getElementById('result').value = parseInt(document.getElementById('result').value) + c;
}
function divmod() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a % b);
document.getElementById('result').value = parseInt(document.getElementById('result').value) + c;
}
<form name="calculator">
<input type="text" id="l1" />
<input type="text" id="l2" />
<br/>
<input type="button" value="+" onclick="add()" />
<br/>
<input type="button" value="-" onclick="sub()" />
<br/>
<input type="button" onclick="mult()" />
<br/>
<input type="button" value="%" onclick="divmod()" />
<input type="button" value="/" onclick="div()" />
<br/>
<input type="button" value="clean" class="class2" />
<br/>
<p style="color:white; font-size:30px;">Result:</p>
<input type="text" id="result" />
<br/>
</form>

I am creating a quiz and want to know if I have to get the value of each choice or is there away to do it short hand

I want to get the user selection for a quiz.
I am doing this by using const choiceA = document.getElementById("A").value;
There are four choices and instead of creating 4 different const could I do something like. const choice = document.getElementById("A", "B"....).value
Or is there any other way to do this short hand?
Any links to good information about gathering user input would be much appreciated too :)
<html>
<form id="formEl">
<h2 id="question"></h2>
<button id="A" type="button" class="userSelection"></button>
<button id="B" type="button" class="userSelection"></button>
<button id="C" type="button" class="userSelection"></button>
<button id="D" type="button" class="userSelection"></button>
<button id="previous" type="button" class="userSelection">Previous</button>
<button id="next" type="button" class="userSelection">Next</button>
<button id="submit">Submit</button>
</form>
<js>
class Question {
constructor(question, ansA, ansB, ansC, ansD, answer) {
this.question = question;
this.ansA = ansA;
this.ansB = ansB;
this.ansC = ansC;
this.ansD = ansD;
this.answer = answer;
};
checkAns(ansSelected, answer) {
if (ansSelected === answer) {
console.log('Well Done')
};
};
};
//Questions
var questionOne = new Question('Where is Creete?', 'Barcalona', 'Greece', 'Dubi', 'Ireland', 'Greece');
var questionTwo = new Question('How many times have Liverppool won the Champions Legue?', '1', '4', '6', '5', '6');
var questionThree = new Question('Where was the first Godfather in the mafia from?', 'Milan', 'Gunoa', 'Rome', 'Napoli', 'Napoli');
//Index of the array with the questions array
var i = 0;
const arrayQuestion = [questionOne, questionTwo, questionThree];
//Selecting the value of the user once clicked
const choiceA = document.getElementById("A").value;
const choiceB = document.getElementById("B").value;
const choiceC = document.getElementById("C").value;
const choiceD = document.getElementById("D").value;
I recommend you to dont use buttonbecause they only execute scripts or onclick,functions,they cant save a variable or a value, it will be much easier to use select
so you can read the selectedIndex
example:
<select name="Class" id="Class">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
//This is for you to see the selected value
<input type="text" name="valorsel" id="valorsel" class="form-control" placeholder="Selected Index Value">
This will be the script
<script>
function myFunction()
{
//Getting the value
var selObj = document.getElementById("Class");
var selValue = selObj.options[selObj.selectedIndex].value;
//Setting Value
document.getElementById("valorsel").value = selValue;
}
</script>
This may be a bit old school. But :) If it has to be a button then you can not just evaluate the form. They will give always their value as you can see in below running code. If we want to abuse buttons we have to be a bit tricky. I use a input field to get and edit the values. Can be hidden for sure afterwards. The native html soloution would be radio buttons if only one answer would be ok or checkboxes if some answers could be ok. the serialize function would then give you all values in a good style. Some suggested option input field which are in my opinion unhandy. But taste is different. in my "getanswer" routine you can easy add some style changes - make the button red if he is active or whatever. I also sort the result to make it easy to compare with the right answer. The html part could be also written automatically in your document.
function changeform(formid,html) {
document.getElementById(formid).nextElementSibling.innerHTML=html;
}
<!DOCTYPE html>
<html>
<body>
<form id="formEl" name="formEl" onsubmit="done(this)">
<div>
<button id="A" type="button" class="userSelection" NAME="A"
VALUE="A"
onclick="edanswer('A')">A</button>
<button id="B" type="button" class="userSelection" NAME="B"
VALUE="B"
onclick="edanswer('B')">B</button>
<button id="C" type="button" class="userSelection" NAME="C"
VALUE="C"
onclick="edanswer('C')">C</button>
<button id="D" type="button" class="userSelection" NAME="D"
VALUE="D"
onclick="edanswer('D')">D</button>
</div>
<input type="submit" value="gotcha">
<input id="result" name="result">
</FORM>
<SCRIPT>
function edanswer(answer) {
result = formEl.elements["result"].value
if (result.indexOf(answer) < 0) {
result = result + answer;
} else {
result = result.replace(answer, "");
}
//sort result to ease further processing / evaluation
arr = result.split('');
arr.sort();
result = arr.join('');
formEl.elements["result"].value = result;
}
function done(x) {
alert(x.result.value);
alert(serialize(x));
// just to clarify the form button issue
// the preferred input type would be a checkbox
// on submit they give sound values without hussle
}
//https://code.google.com/archive/p/form-serialize/downloads
function serialize(form) {
if (!form || form.nodeName !== "FORM") {
return;
}
var i, j, q = [];
for (i = form.elements.length - 1; i >= 0; i = i - 1) {
if (form.elements[i].name === "") {
continue;
}
switch (form.elements[i].nodeName) {
case 'INPUT':
switch (form.elements[i].type) {
case 'text':
case 'hidden':
case 'password':
case 'button':
case 'reset':
case 'submit':
q.push(form.elements[i].name + "=" +
encodeURIComponent(form.elements[i].value));
break;
case 'checkbox':
case 'radio':
if (form.elements[i].checked) {
q.push(form.elements[i].name + "=" +
encodeURIComponent(form.elements[i].value));
}
break;
case 'file':
break;
}
break;
case 'TEXTAREA':
q.push(form.elements[i].name + "=" +
encodeURIComponent(form.elements[i].value));
break;
case 'SELECT':
switch (form.elements[i].type) {
case 'select-one':
q.push(form.elements[i].name + "=" +
encodeURIComponent(form.elements[i].value));
break;
case 'select-multiple':
for (j = form.elements[i].options.length - 1; j >= 0; j = j -
1) {
if (form.elements[i].options[j].selected) {
q.push(form.elements[i].name + "=" +
encodeURIComponent(form.elements[i].options[j].value));
}
}
break;
}
break;
case 'BUTTON':
switch (form.elements[i].type) {
case 'reset':
case 'submit':
case 'button':
q.push(form.elements[i].name + "=" +
encodeURIComponent(form.elements[i].value));
break;
}
break;
}
}
return q.join("&");
}
</SCRIPT>
</body>
</html>

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