Issues building a calculator in JS - javascript

I'm a complete beginner at this and have started learning javascript through free code camp. I'm trying to write a program to make a calculator using basic javascript. My calculator seems to work fine except for it has a couple of issues that I want to fix. Edit to clarify what I'm asking for help here. Please run my codes in the snippet below with the following operation and you'll understand what I'm asking. Type 9-2 then hit '=' the calculator should display '7'. If you type a '2' immediately after the '7' is displayed, it will give you a '72' on the screen which is what I don't want it to do. I want it to reset to a blank screen. The other issue I have is a repeating display of operators. I've used the codes supplied by other commenters but they don't seem to work. I will keep searching for solution. Thank you all.
the operators: +, -, *, / and . are at this time can be repeated when pushing the button repeatedly. How do I create a function to only allow it to be displayed once.
After hitting the 'equal' button with the result displayed on the screen. If I pressed another number it would add on to the result instead of starting on a new screen. I need for it to reset and start a new using my current codes.
Any guidance and direction is appreciated. I have search Google for days now and still stuck. I'm also terrible at logic which I'm trying my best to wrap my head around this. Thanks.
var show = document.getElementById('display');
var reset = false;
function clear() {
if (reset) {
show.value = '';
reset = false;
}
}
function toScreen(x) {
clear();
show.value += x;
if (x === 'c') {
show.value = '';
}
}
function answer() {
x = show.value;
x = eval(x);
show.value = x;
reset = false;
}
function power() {
x = show.value;
x = eval(x * x);
show.value = x;
}
function backspace() {
var num = show.value;
var len = num.length - 1;
var newNum = num.substring(0, len);
show.value = newNum;
}
function percent() {
x = show.value;
x = eval(x / 100);
show.value = x;
}
function opposite() {
var n = show.value;
n = n * -1;
show.value = n;
}
function sqrt() {
var number = show.value;
var ans = Math.sqrt(number);
if (number < 0)
ans = "Try a positive number!";
show.value = ans;
}
function pie() {
var pi = show.value;
var result = Math.PI;
show.value = result;
}
<form>
<input type="text" id="display" disabled><br>
<input type="button" value="C" id="keys" onclick="toScreen('c')">
<input type="button" value="DEL" id="keys" onclick="backspace()">
<input type="button" value="π" id="keys" onclick="pie()">
<input type="button" value="+/-" id="keys" onclick="opposite()"><br>
<input type="button" value="√" id="keys" onclick="sqrt()">
<input type="button" value="%" id="keys" onclick="percent()">
<input type="button" value="x^2" id="keys" onclick="power()">
<input type="button" value="+" id="keys" onclick="toScreen('+')"><br>
<input type="button" value="9" id="keys" onclick="toScreen('9')">
<input type="button" value="8" id="keys" onclick="toScreen('8')">
<input type="button" value="7" id="keys" onclick="toScreen('7')">
<input type="button" value="-" id="keys" onclick="toScreen('-')"><br>
<input type="button" value="6" id="keys" onclick="toScreen('6')">
<input type="button" value="5" id="keys" onclick="toScreen('5')">
<input type="button" value="4" id="keys" onclick="toScreen('4')">
<input type="button" value="*" id="keys" onclick="toScreen('*')"><br>
<input type="button" value="3" id="keys" onclick="toScreen('3')">
<input type="button" value="2" id="keys" onclick="toScreen('2')">
<input type="button" value="1" id="keys" onclick="toScreen('1')">
<input type="button" value="/" id="keys" onclick="toScreen('/')"><br>
<input type="button" value="0" id="keys" onclick="toScreen('0')">
<input type="button" value="." id="keys" onclick="toScreen('.')">
<input type="button" value="=" id="equal" onclick="answer()"><br>
</form>

See the codes
Here is the perfectly working code. You can replace x with i some places like:
function power() {
x = eval(i * i);
show.value = x;
reset = true;
}
Problem fixed:
Your 1st & 2nd problem
Your code didn't check is input starting from a num. or operator (/1, *1)
Your code didn't check for invalid input (1+, 1+1+ etc)
Your code also not clear screen (like in case of anser) after power Pi etc
Your function like PI Power not check if input is a number (power of 8*) see the power function:
var show = document.getElementById('display');
var reset = false;
var i = ""; //store what is typed
function clear() {
if (reset) {
i = '';
show.value = i;
reset = false;
}
}
function toScreen(x) {
clear();
if (x === "+" || x === "-" || x === "*" || x === "/" || x === ".") {
if (i.charAt(i.length - 1) === x) {
return false;
}
if (i.length === 0) {
return false;
}
}
i += x;
if (x === 'c') {
i = '';
}
show.value = i;
}
function answer() {
var op = ["+", "-", "*", ".", "/"];
for (a=0; a<op.length; a++) {
if (i.charAt(i.length - 1) === op[a]) {
alert("Wrong input");
return false;
}
}
x = show.value;
x = eval(x);
show.value = x;
reset = true;
}
function power() {
if (isNaN(i)) {
alert("please enter a valid number");
return false;
}
x = show.value;
x = eval(x * x);
show.value = x;
reset = true;
}
function backspace() {
var num = show.value;
var len = num.length - 1;
var newNum = num.substring(0, len);
show.value = newNum;
reset = true;
}
function percent() {
x = show.value;
x = eval(x / 100);
show.value = x;
reset = true;
}
function opposite() {
var n = show.value;
n = n * -1;
show.value = n;
reset = true;
}
function sqrt() {
var number = show.value;
var ans = Math.sqrt(number);
if (number < 0)
ans = "Try a positive number!";
show.value = ans;
reset = true;
}
function pie() {
var pi = show.value;
var result = Math.PI;
show.value = result;
reset = true;
}
<form>
<input type="text" id="display" disabled><br>
<input type="button" value="C" id="keys" onclick="toScreen('c')">
<input type="button" value="DEL" id="keys" onclick="backspace()">
<input type="button" value="π" id="keys" onclick="pie()">
<input type="button" value="+/-" id="keys" onclick="opposite()"><br>
<input type="button" value="√" id="keys" onclick="sqrt()">
<input type="button" value="%" id="keys" onclick="percent()">
<input type="button" value="x^2" id="keys" onclick="power()">
<input type="button" value="+" id="keys" onclick="toScreen('+')"><br>
<input type="button" value="9" id="keys" onclick="toScreen('9')">
<input type="button" value="8" id="keys" onclick="toScreen('8')">
<input type="button" value="7" id="keys" onclick="toScreen('7')">
<input type="button" value="-" id="keys" onclick="toScreen('-')"><br>
<input type="button" value="6" id="keys" onclick="toScreen('6')">
<input type="button" value="5" id="keys" onclick="toScreen('5')">
<input type="button" value="4" id="keys" onclick="toScreen('4')">
<input type="button" value="*" id="keys" onclick="toScreen('*')"><br>
<input type="button" value="3" id="keys" onclick="toScreen('3')">
<input type="button" value="2" id="keys" onclick="toScreen('2')">
<input type="button" value="1" id="keys" onclick="toScreen('1')">
<input type="button" value="/" id="keys" onclick="toScreen('/')"><br>
<input type="button" value="0" id="keys" onclick="toScreen('0')">
<input type="button" value="." id="keys" onclick="toScreen('.')">
<input type="button" value="=" id="equal" onclick="answer()"><br>
</form>

function answer() {
x = show.value;
x = eval(x);
show.value = x;
reset = true;
}
Change the reset to true, so that it clears the show.value to be an empty string, that solves nr.2 for you

Edit your toScreen() function to only add your operator if it was
not previously typed:
function toScreen(x) {
clear();
var notTwice = ['+', '-', '*', '/', '.']; //List of chars that should not be repeated
if(notTwice.indexOf(x) > -1){
if(show.value.slice(-1) != x){ //Only type it if it wasn't typed right before
show.value += x;
}
}
else{
show.value += x;
}
if (x === 'c') {
show.value = '';
}
}
Just set reset to false in your answer() function.
Here is a working snippet for you :
var show = document.getElementById('display');
var reset = false;
var i = ""; //store what is typed
function clear() {
if (reset) {
i = '';
show.value = i;
reset = false;
}
}
function toScreen(x) {
clear();
var notTwice = ['+', '-', '*', '/', '.']; //List of chars that should not be repeated
if(notTwice.indexOf(x) > -1){
if(show.value.slice(-1) != x){ //Only type it if it wasn't typed right before
show.value += x;
}
}
else{
show.value += x;
}
if (x === 'c') {
show.value = '';
}
}
function answer() {
var op = ["+", "-", "*", ".", "/"];
for (a=0; a<op.length; a++) {
if (i.charAt(i.length - 1) === op[a]) {
alert("Wrong input");
return false;
}
}
x = show.value;
x = eval(x);
show.value = x;
reset = false;
}
function power() {
if (isNaN(i)) {
alert("please enter a valid number");
return false;
}
x = show.value;
x = eval(x * x);
show.value = x;
reset = true;
}
function backspace() {
var num = show.value;
var len = num.length - 1;
var newNum = num.substring(0, len);
show.value = newNum;
reset = true;
}
function percent() {
x = show.value;
x = eval(x / 100);
show.value = x;
reset = true;
}
function opposite() {
var n = show.value;
n = n * -1;
show.value = n;
reset = true;
}
function sqrt() {
var number = show.value;
var ans = Math.sqrt(number);
if (number < 0)
ans = "Try a positive number!";
show.value = ans;
reset = true;
}
function pie() {
var pi = show.value;
var result = Math.PI;
show.value = result;
reset = true;
}
<form>
<input type="text" id="display" disabled><br>
<input type="button" value="C" id="keys" onclick="toScreen('c')">
<input type="button" value="DEL" id="keys" onclick="backspace()">
<input type="button" value="π" id="keys" onclick="pie()">
<input type="button" value="+/-" id="keys" onclick="opposite()"><br>
<input type="button" value="√" id="keys" onclick="sqrt()">
<input type="button" value="%" id="keys" onclick="percent()">
<input type="button" value="x^2" id="keys" onclick="power()">
<input type="button" value="+" id="keys" onclick="toScreen('+')"><br>
<input type="button" value="9" id="keys" onclick="toScreen('9')">
<input type="button" value="8" id="keys" onclick="toScreen('8')">
<input type="button" value="7" id="keys" onclick="toScreen('7')">
<input type="button" value="-" id="keys" onclick="toScreen('-')"><br>
<input type="button" value="6" id="keys" onclick="toScreen('6')">
<input type="button" value="5" id="keys" onclick="toScreen('5')">
<input type="button" value="4" id="keys" onclick="toScreen('4')">
<input type="button" value="*" id="keys" onclick="toScreen('*')"><br>
<input type="button" value="3" id="keys" onclick="toScreen('3')">
<input type="button" value="2" id="keys" onclick="toScreen('2')">
<input type="button" value="1" id="keys" onclick="toScreen('1')">
<input type="button" value="/" id="keys" onclick="toScreen('/')"><br>
<input type="button" value="0" id="keys" onclick="toScreen('0')">
<input type="button" value="." id="keys" onclick="toScreen('.')">
<input type="button" value="=" id="equal" onclick="answer()"><br>
</form>

Related

How to calculate discount for price and clear form when radio button is changed

1) I am trying to calculate discount for price with this code but it does not work.
2) I want to clear form when the radio button is changed. Example the size is M and fill number in quantity input only If I change the size, the form will be clear or after amount show me If I change size, the form will be clear too.
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', total)
});
var total = function () {
var s = Number(document.querySelector('input[name=size]:checked').value);
var q = Number(document.getElementById('qty').value);
var m = document.querySelector('input[name=member]:checked').value;
var result;
if(s && q && m) {
if(q >= 1) {
if(s == 'S') {
result = s * q;
} else if(s == 'M') {
result = s * q;
} else if(s == 'L') {
result = s * q;
} else {
result = s * q;
}
result -= m === "YES" ? result*5/100 : 0;
} else {
result = " ";
}
} else {
result = " ";
}
document.getElementById('amount').innerHTML = result.toFixed(2);
}
const clearForm = () => {
document.getElementById('myForm').reset();
}
<form id="myForm">
<div>
<p>Size:
<input type="radio" name="size" id="S" value="249">S
<input type="radio" name="size" id="M" value="269">M
<input type="radio" name="size" id="L" value="309">L
<input type="radio" name="size" id="XL" value="319">XL
</p>
</div>
<p>Quantity:
<input type="text" name="qty" id="qty">
</p>
<p>Member:
<input type="radio" name="member" value="YES">YES
<input type="radio" name="member" value="NO">NO
</p>
<p>Amount: $
<input type="text" name="amount" id="amount" readonly>
</p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Reset</button>
</form>
Your calculations are working as expected.
You have one problem in your Code:
document.getElementById('amount').innerHTML = result.toFixed(2); //Here with innerHTML
inputs cannot contain html. They can only contain a value. The property innerHTML is not ideal for input elements. What you are looking for is:
document.getElementById('amount').value = result.toFixed(2);
You must set the value of your amount, not innerHTML.
I have just edited your Snipped. Notice the changes I made on your code. A lot of stuff were unnecessary. Like your multiple if statements checking for 'S', 'M' ... Because at the end they all lead to the same calculation expression.
window.addEventListener("load", () => {
// clear then textboxes on Size change
document.querySelectorAll("input[name=size]").forEach(input=>{
input.addEventListener('change', ()=>{
clearTextBoxes();
});
});
});
var computeTotal = () =>
{
var s = document.querySelector('input[name=size]:checked').value;
var q = document.getElementById('qty').value;
var m = document.querySelector('input[name=member]:checked').value;
var result; //initialize to empty string
if(s && q && m && q >= 1) {
result = s * q;
result -= m === "YES" ? result*5/100 : 0;
}
// Change innerHTML to value
document.getElementById('amount').value = result == undefined ? " " : result.toFixed(2);
}
var clearTextBoxes = () => {
document.getElementById("qty").value = "";
document.getElementById("amount").value = "";
}
const clearForm = () => {
document.getElementById('myForm').reset();
}
<form id="myForm">
<p>Member:
<input type="radio" name="member" value="YES">YES
<input type="radio" name="member" value="NO">NO
</p>
<div>
<p>Size:
<input type="radio" name="size" id="S" value="249">S
<input type="radio" name="size" id="M" value="269">M
<input type="radio" name="size" id="L" value="309">L
<input type="radio" name="size" id="XL" value="319">XL
</p>
</div>
<p>Quantity:
<input type="number" name="qty" id="qty">
</p>
<p>Amount: $
<input type="text" name="amount" id="amount" readonly>
</p>
<button type="button" id="calculate" onclick="computeTotal()">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Reset</button>
</form>
You need to clear the input fields when radio button changes. Find the working demo below
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', total)
});
var total = function() {
var s = Number(document.querySelector('input[name=size]:checked').value);
var q = Number(document.getElementById('qty').value);
var m = document.querySelector('input[name=member]:checked').value;
var result;
if (s && q && m) {
if (q >= 1) {
if (s == 'S') {
result = s * q;
} else if (s == 'M') {
result = s * q;
} else if (s == 'L') {
result = s * q;
} else {
result = s * q;
}
result -= m === "YES" ? result * 5 / 100 : 0;
} else {
result = " ";
}
} else {
result = " ";
}
document.getElementById('amount').value = result.toFixed(2);
}
const clearForm = () => {
document.getElementById('myForm').reset();
}
// Add event listener to all radio items and add the clearfields logic
var memberRadios = document.querySelectorAll('input[type=radio][name="member"]');
var sizeRadios = document.querySelectorAll('input[type=radio][name="size"]');
Array.prototype.forEach.call(memberRadios, function(radio) {
radio.addEventListener('change', clearFields);
});
Array.prototype.forEach.call(sizeRadios, function(radio) {
radio.addEventListener('change', clearFields);
});
function clearFields(event) {
document.getElementById('qty').value = null;
document.getElementById('amount').value = null;
}
<form id="myForm">
<p>Member:
<input type="radio" name="member" value="YES">YES
<input type="radio" name="member" value="NO">NO
</p>
<div>
<p>Size:
<input type="radio" name="size" id="S" value="249">S
<input type="radio" name="size" id="M" value="269">M
<input type="radio" name="size" id="L" value="309">L
<input type="radio" name="size" id="XL" value="319">XL
</p>
</div>
<p>Quantity:
<input type="text" name="qty" id="qty">
</p>
<p>Amount: $
<input type="text" name="amount" id="amount" readonly>
</p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Reset</button>
</form>

Appending numeric values to a form box upon button clicks

I am programming a calculator for an assignment, and I am struggling to append values of each button click to my display box. For example, if I click the button "4" and then "5", I want the display to output "45", and so on, in order to evaluate what's in the display box. When I click a button on the calculator, the number displays correctly, but no concurrent values will append afterwards. I have also created the equal function to correctly function if display is typed in on keyboard.
<!DOCTYPE html>
<head>
<link href="project4.css" rel="stylesheet">
<title>Calculator</title>
</head>
<body>
<div id="calculator">
<h3>Calculator</h3>
<input type="text" id="display" onClick= "append()"><br />
<input type="button" value="mrc" class="memory">
<input type="button" value="m+" class="memory">
<input type="button" value="m-" class="memory">
<input type="button" value="/" class="operator" onClick= "setDivide()"><br />
<input type="button" value="7" class="number" onClick= "setSeven()">
<input type="button" value="8" class="number" onClick= "setEight()">
<input type="button" value="9" class="number" onClick= "setNine()">
<input type="button" value="*" class="operator" onClick= "setMultiply()"><br />
<input type="button" value="4" class="number" onClick= "setFour()">
<input type="button" value="5" class="number" onClick= "setFive()">
<input type="button" value="6" class="number" onClick= "setSix()">
<input type="button" value="+" class="operator" onClick="setAdd()"><br />
<input type="button" value="1" class="number" onClick= "setOne()">
<input type="button" value="2" class="number" onClick= "setTwo()">
<input type="button" value="3" class="number" onClick= "setThree()">
<input type="button" value="-" class="operator" onClick= "setSubtract()"><br />
<input type="button" value="0" class="number" onClick= "setZero()">
<input type="button" value="." value="." class="number" onClick= "setDecimal()">
<input type="button" value="C" class="clear" onClick= "setClear()">
<input type="button" value="=" class="equal" onClick= "setEquals()">
</div>
<!--Jquery script-->
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<!--Javascript script-->
<script type="text/javascript" src="project4.js">
//Declaring all
variables necessary
var seven, eight, nine, four, five, six, one, two, three, zero, decimal,
divide, multiply, add, subtract, clear, answer, expression;
//All functions to set the keys to values upon clicking
function setSeven() {
seven = 7;
document.getElementById("display").value = seven;
}
function setEight() {
eight = 8;
document.getElementById("display").value = eight;
}
function setNine() {
nine = 9;
document.getElementById("display").value = nine;
}
function setFour() {
four = 4;
document.getElementById("display").value = four;
}
function setFive() {
five = 5;
document.getElementById("display").value = five;
}
function setSix() {
six = 6;
document.getElementById("display").value = six;
}
function setOne() {
one = 1;
document.getElementById("display").value = one;
}
function setTwo() {
two = 2;
document.getElementById("display").value = two;
}
function setThree() {
three = 3;
document.getElementById("display").value = three;
}
function setZero() {
zero = 0;
document.getElementById("display").value = zero;
}
function setDecimal() {
decimal = ".";
document.getElementById("display").value = decimal;
}
function setDivide() {
divide = "/";
document.getElementById("display").value = divide;
}
function setMultiply() {
multiply = "*";
document.getElementById("display").value = multiply;
}
function setAdd() {
add = "+";
document.getElementById("display").value = add;
}
function setSubtract() {
subtract = "-";
document.getElementById("display").value = subtract;
}
function setClear() {
clear = "";
document.getElementById("display").value = clear;
}
function setEquals() {
expression = (document.getElementById("display").value);
answer = eval(expression);
document.getElementById("display").value = answer;
}
function append() {
var array = new Array(document.getElementById("display").value);
var newDisplay = array.append("display",
document.getElementById("display").value);
document.getElementById("display").value = newDisplay;
}
</script>
</body>
document.getElementById("display").value+ = answer;

Adding Javascript value to hidden input

I'm trying to add a JavaScript variable to a hidden input field. How would I do this?
HTML:
<button type="button" class="submitFormOnClick btn btn-warning pull-right"
style="margin-bottom:15px; margin-top:15px;" id="bet">Bet
</button>
<input type="hidden" name="controller" value="keno">
<input type="hidden" name="task" id="task" value="">
<input type="hidden" name="pickednumbers" id="pickednumbers">
JavaScript:
<script type="text/javascript">
var inc = 0;
var pickednumbers = [];
function myFunction(elmnt, color, id)
{
if(pickednumbers.length >= 20)
{
return false;
}
if (pickednumbers.indexOf(id) === -1)
{
pickednumbers.push(id);
elmnt.style.background = color;
inc = inc + 1;
if(inc >= 20)
{
document.getElementById('onColor').setAttribute("style", "background-color:green");
}
}
else
{
return false;
}
}
</script>
What I need:
All I want is to have the variable pickednumbers be sent with the input type hidden.
You may simply do this :
var inc = 0;
var pickednumbers = [2,3,4,8];
document.getElementById("pickednumbers").setAttribute("value",JSON.stringify(pickednumbers));
<button type="button" class="submitFormOnClick btn btn-warning pull-right" style="margin-bottom:15px;margin-top:15px;" id="bet">Bet
</button>
<input type="hidden" name="controller" value="keno">
<input type="hidden" name="task" id="task" value="">
<input type="hidden" name="pickednumbers" id="pickednumbers">

javascript calculator input background

Hi just out of educational purpose im trying to do a few things with my calculator i did, im trying to get the display to change color depending on result, this is the closest i've come, but it just shows red no matter what the result is, so what more do i need to add?
<script>
function checkNum() {
var x = document.kalk.disp.value;
if (x.match(/[a-zA-Z]+/)) {
kalk.disp.value=("Endast siffror!");
kalk.disp.style.background = "red";
} else {
kalk.disp.value = eval(x);
(eval.value===0)
kalk.disp.style.background = "green";
(eval.value>=1)
kalk.disp.style.background = "blue";
(eval.value<=-1)
kalk.disp.style.background = "red";
}
}
</script>
here's the html
<form name="kalk">
<input type="text" name="disp" >
<br>
<input type="button" value="7" OnClick="kalk.disp.value+='7'">
<input type="button" value="8" OnClick="kalk.disp.value+='8'">
<input type="button" value="9" OnClick="kalk.disp.value+='9'">
<input type="button" value="*" OnClick="kalk.disp.value+='*'">
<br>
<input type="button" value="4" OnClick="kalk.disp.value+='4'">
<input type="button" value="5" OnClick="kalk.disp.value+='5'">
<input type="button" value="6" OnClick="kalk.disp.value+='6'">
<input type="button" value="-" OnClick="kalk.disp.value+='-'">
<br>
<input type="button" value="1" OnClick="kalk.disp.value+='1'">
<input type="button" value="2" OnClick="kalk.disp.value+='2'">
<input type="button" value="3" OnClick="kalk.disp.value+='3'">
<input type="button" value="+" OnClick="kalk.disp.value+='+'">
<br>
<input type="button" value="C" OnClick="kalk.disp.value=''">
<input type="button" value="0" OnClick="kalk.disp.value+='0'">
<input type="button" value="." OnClick="kalk.disp.value+='.'">
<input type="button" value="=" OnClick="checkNum()" >
</form>
its basically this that i have added
(eval.value===0)
kalk.disp.style.background = "green";
(eval.value>=1)
kalk.disp.style.background = "blue";
(eval.value<=-1)
kalk.disp.style.background = "red";
You are using the eval wrong.
You need some if-statements or something like this:
function checkNum() {
var x = document.kalk.disp.value;
if (x.match(/[a-zA-Z]+/)) {
kalk.disp.value = ("Endast siffror!");
kalk.disp.style.background = "red";
} else {
var result = eval(x);
kalk.disp.value = result;
if (result > 0) {
kalk.disp.style.background = "blue";
} else if (result === 0) {
kalk.disp.style.background = "green";
} else {
kalk.disp.style.background = "red";
}
}
}
fiddle
function checkNum() {
var x = document.kalk.disp.value;
if (x.match(/[a-zA-Z]+/)) {
kalk.disp.value = ("Endast siffror!");
kalk.disp.style.background = "red";
} else {
var result = eval(x);
kalk.disp.value = result;
if (result > 0) {
kalk.disp.style.background = "blue";
} else if (result === 0) {
kalk.disp.style.background = "green";
} else {
kalk.disp.style.background = "red";
}
}

Getting the value of a textbox then parsing it

I am creating a simple calculator in javascript but how come each time I added numbers it only adds the the first half of the 2nd number? for example
first input: 55
second input: 55
then it will give me an answer of 60.
it only adds the lower half of the 2nd input.
here's my code
var fnum;
var secondNum;
var operation;
function msg(val){
document.getElementById("fnumtext").value += val;
fnum = val;
}
function showOperation(oper){
document.getElementById("fnumtext").value ="";
document.getElementById("operation").value = oper;
operation = oper;
}
function equal(){
secondNum = document.getElementById("fnumtext").value;
alert(secondNum+operation);
if(document.getElementById("operation").value == "+"){
var x = parseInt(fnum)+parseInt(secondNum);
alert(x);
}else if(document.getElementById("operation").value == "-"){
var x = parseInt(fnum)-parseInt(secondNum);
alert(x);
}else if(document.getElementById("operation").value == "*"){
var x = parseInt(fnum)*parseInt(secondNum);
alert(x);
}else if(document.getElementById("operation").value == "/"){
var x = parseInt(fnum)/parseInt(secondNum);
alert(x);
}else{
alert("choose some Operation");
}
}
my HTML
body>
<input id = "fnumtext"type="text" name="firstnum" /><br />
<input id = "operation" type="text" name="secondnum" /><br />
<input type="button" value="1" onclick="msg('1')" />
<input type="button" value="2" onclick="msg('2')" />
<input type="button" value="3" onclick="msg('3')" /></br>
<input type="button" value="4" onclick="msg('4')" />
<input type="button" value="5" onclick="msg('5')" />
<input type="button" value="6" onclick="msg('6')" /><br/>
<input type="button" value="7" onclick="msg('7')" />
<input type="button" value="8" onclick="msg('8')" />
<input type="button" value="9" onclick="msg('9')" /></br>
<input type="button" value="0" onclick="msg('0')" /></br>
<input type="button" value="+" onclick="showOperation('+')" />
<input type="button" value="*" onclick="showOperation('*')" />
<input type="button" value="/" onclick="showOperation('/')" />
<input type="button" value="-" onclick="showOperation('-')" />
<input type="button" value="DO ZEH OPERATION!" onclick="equal()" />
</body>
In msg, you set the value of fnum rather than appending it. Try changing that to +=.
function msg(val){
document.getElementById("fnumtext").value += val;
fnum += val; // changed this line
}
First you need to keep track whether this is a first operand you're entering now or the second one.
Second, you must add current digit's value to the already accumulated values, not override them.
var fnum;
var secondNum;
var operation;
var firstOperand = true;
function msg(val) {
document.getElementById("fnumtext").value += val;
if (firstOperand) {
fnum = document.getElementById("fnumtext").value;
}
}
function showOperation(oper)
{
firstOperand = false;
document.getElementById("fnumtext").value = "";
document.getElementById("operation").value = oper;
operation = oper;
}
function equal() {
secondNum = document.getElementById("fnumtext").value;
alert(secondNum+operation);
if (document.getElementById("operation").value == "+") {
var x = parseInt(fnum) + parseInt(secondNum);
alert(x);
} else if (document.getElementById("operation").value == "-") {
var x = parseInt(fnum) - parseInt(secondNum);
alert(x);
} else if (document.getElementById("operation").value == "*") {
var x = parseInt(fnum) * parseInt(secondNum);
alert(x);
} else if (document.getElementById("operation").value == "/") {
var x = parseInt(fnum) / parseInt(secondNum);
alert(x);
} else {
alert("choose some Operation");
}
firstOperand = true;
document.getElementById("fnumtext").value = "";
}

Categories