I want to add features to a basic Javascript calculator, but can't get the decimal button to append to the display.
I can get as far as console.logging the product I want, but I can't get the decimal to push to the display. If I used printOutput(output) instead of console.log(output), nothing happens. No error or output.
//GET TEXT VALUES FOR HISTORY AND OUTPUT
function getHistory() {
return document.querySelector(".history-value").innerText;
}
function getOutput() {
return document.querySelector(".output-value").innerText;
}
//PRINT HISTORY AND OUTPUT VALUES TO NUM VALUE
function printHistory(num) {
document.querySelector(".history-value").innerText = num;
}
function printOutput(num) {
if (num == "") {
document.querySelector(".output-value").innerText = num;
} else {
document.querySelector(".output-value").innerText = getFormattedNumber(num);
}
}
//NUMBER FORMATS
function getFormattedNumber(num) {
if (num == "") {
return "";
}
var n = Number(num);
var value = n.toLocaleString("en");
return value;
}
function reverseNumberFormat(num) {
return Number(num.replace(/,/g, ''));
}
//OPERATOR AND NUMBER FUNCTIONS
var operator = document.getElementsByClassName("operator");
for (var i = 0; i < operator.length; i++) {
operator[i].addEventListener('click', function () {
if (this.id == "clear") {
printHistory("");
printOutput("");
}
else if (this.id == "backspace") {
var output = reverseNumberFormat(getOutput()).toString();
if (output) {
output = output.substr(0, output.length - 1);
printOutput(output);
}
}
else {
var output = getOutput();
var history = getHistory();
if (output == "" && history != "") {
output = output == "" ?
output : reverseNumberFormat(output);
if (isNaN(history[history.length - 1])) {
history = history.substr(0, history.length - 1);
}
}
if (output != "" || history != "") {
output = reverseNumberFormat(output);
history = history + output;
if (this.id == "=") {
var result = eval(history);
printOutput(result);
printHistory("");
}
else {
history = history + this.id;
printHistory(history);
printOutput("");
}
}
}
});
}
var number = document.getElementsByClassName("number");
for (var i = 0; i < number.length; i++) {
number[i].addEventListener('click', function () {
var output = reverseNumberFormat(getOutput());
if (this.id == ".") {
output += this.id;
console.log(output);
}
else if (output != NaN) {
output = output + this.id;
printOutput(output);
}
});
}
printOutput("")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<title>calcApp</title>
</head>
<body>
<div class="container">
<div class="calculator">
<div class="results">
<div class="history">
<p class="history-value"></p>
</div>
<div class="output">
<p class="output-value"></p>
</div>
</div>
<div class="keyboard">
<button class="operator" id="clear">C</button>
<button class="operator" id="backspace">CE</button>
<button class="operator" id="%">%</button>
<button class="operator" id="/">÷</button>
<button class="number" id="7">7</button>
<button class="number" id="8">8</button>
<button class="number" id="9">9</button>
<button class="operator" id="*">×</button>
<button class="number" id="4">4</button>
<button class="number" id="5">5</button>
<button class="number" id="6">6</button>
<button class="operator" id="-">-</button>
<button class="number" id="1">1</button>
<button class="number" id="2">2</button>
<button class="number" id="3">3</button>
<button class="operator" id="+">+</button>
<button class="empty" id="empty"></button>
<button class="number" id="0">0</button>
<button class="number" id="." data-action="decimal">•</button>
<button class="operator" id="=">=</button>
</div>
</div>
</container>
<script src="script.js"></script>
</body>
</html>
The specific code I attempted is:
var number = document.getElementsByClassName("number");
for (var i = 0; i < number.length; i++) {
number[i].addEventListener('click', function () {
var output = reverseNumberFormat(getOutput());
if (this.id == ".") {
output += this.id;
console.log(output);
}
else if (output != NaN) {
output = output + this.id;
printOutput(output);
}
});
}
In short: I want to create a decimal button that adds a decimal to the existing displayed numbers, and then allows operations using decimals. I'm only asking for help on the display issue.
Related
I am trying to make a calculator, simply my problem is this:
Page refreshes.
User clicks on any number and the number gets added to the First Number: nums_clicked h1.
If user clicks on an operator sign(+ - *), the clicked boolean becomes true.
If clicked is true, add the numbers clicked to the Second Number: nums_clicked
My problem is even if I click on an operator sign, it keeps adding the numbers I am clicking to the First Number: nums_clicked h1, why is that happening? It even happens while clicked is TRUE!
My
let numbers = [];
let first_num = "";
let second_num = "";
let clicked = false;
let result = false;
for (var i = 0; i < 9; i++) {
numbers[i] = parseInt(document.querySelectorAll("button")[i].innerText);
}
for (var i = 9; i < 12; i++) {
document.querySelectorAll("button")[i].addEventListener("click", function() {
clicked = true;
});
}
if (!clicked && !result) {
for (let i = 0; i < 9; i++) {
if (clicked) {
break;
}
document.querySelectorAll("button")[i].addEventListener("click",
function() {
console.log("clicked = " + clicked);
first_num += this.innerText;
document.getElementById("firstNumber").innerText = "Number1: " + first_num;
});
}
}
if (clicked && !result) {
for (let i = 0; i < 9; i++) {
document.querySelectorAll("button")[i].addEventListener("click",
function() {
second_num += this.innerText;
document.getElementById("secondNumber").innerText = "Number2: " + second_num;
});
}
}
document.getElementById("result-btn").addEventListener("click",
function() {
result = true;
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/styles.css">
<title></title>
</head>
<body>
<div class="container">
<button type="button" name="button">1</button>
<button type="button" name="button">2</button>
<button type="button" name="button">3</button>
<br>
<button type="button" name="button">4</button>
<button type="button" name="button">5</button>
<button type="button" name="button">6</button>
<br>
<button type="button" name="button">7</button>
<button type="button" name="button">8</button>
<button type="button" name="button">9</button>
<br>
<br>
<button type="button" name="button">+</button>
<button type="button" name="button">*</button>
<button type="button" name="button">-</button>
<br>
<button id="result-btn" type="button" name="button">Result</button>
<h1 id="firstNumber">First Number: </h1>
<h1 id="secondNumber">Second Number: </h1>
<h1 id="result">Result: </h1>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Code:
Screenshot of index.html (Red part while clicked=false and blue part is while clicked=true:
Your main issue was that you were never creating the click events for the second number, because those were behind the if(!result.... Like Barmar mentioned, even if you created the click events for the second number, the events from the first number would be triggered also and it would still not work. Also you did not had anything for setting the actual results.
I made some changes on your code to make it simpler to understand, but still trying to follow your logic. Here you go:
let first_num;
let second_num;
let operation;
for (var i = 9; i < 12; i++) {
document.querySelectorAll('button')[i].addEventListener('click', function () {
operation = this.innerText;
});
}
for (let i = 0; i < 9; i++) {
document.querySelectorAll('button')[i].addEventListener('click', function () {
if (!operation) {
document.getElementById('firstNumber').innerText += this.innerText;
} else {
document.getElementById('secondNumber').innerText += this.innerText;
}
});
}
document.getElementById('result-btn').addEventListener('click', function () {
first_num = document.getElementById('firstNumber').innerText;
second_num = document.getElementById('secondNumber').innerText;
document.getElementById('result').innerText = calculate(
parseInt(first_num),
parseInt(second_num),
operation
);
});
function calculate(a, b, operation) {
if (operation === '+') {
return sum(a, b);
} else if (operation === '-') {
return minus(a, b);
} else if (operation === '*') {
return multiply(a, b);
}
}
function sum(a, b) {
return a + b;
}
function minus(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
<div class="container">
<button type="button" name="button">1</button>
<button type="button" name="button">2</button>
<button type="button" name="button">3</button>
<br />
<button type="button" name="button">4</button>
<button type="button" name="button">5</button>
<button type="button" name="button">6</button>
<br />
<button type="button" name="button">7</button>
<button type="button" name="button">8</button>
<button type="button" name="button">9</button>
<br />
<br />
<button type="button" name="button">+</button>
<button type="button" name="button">*</button>
<button type="button" name="button">-</button>
<br />
<button id="result-btn" type="button" name="button">Result</button>
<h1>First Number: <span id="firstNumber"></span></h1>
<h1>Second Number: <span id="secondNumber"></span></h1>
<h1>Result: <span id="result"></span></h1>
</div>
How can you store a innerHTML value into a global string that can be used in other functions?
I'm doing the calculator project
For example I use this function to check if a input has a value and add the value to the input. But I want to store this variable globally so it can be used everywhere. How can you do that?
var select = document.querySelector('#buttons')
var operating = document.querySelector('#operators')
select.addEventListener('click', selector)
operating.addEventListener('click', operatorSign)
let result;
console.log(result)
function selector(event) {
let target = event.target;
if (target.matches('button')) {
let value = target.innerHTML
let result = document.querySelector('#output').value += value
}}
function operatorSign(e) {
let operator = e.target;
if (operator.matches('button')) {
let value = operator.innerHTML
if (value === "+") {
return add(a, b)
} else if (value === "-") {
return subtract(a, b)
} else if (value === "*") {
return multiply(a, b)
} else if (value === "/") {
return divide(a, b)
} else {
return null
}
}
}
HTML for the selector:
<body>
<button type="button" name="button" id="clear">Clear</button>
<div id="buttons">
<button type="button" name="button" id="button">1</button>
<button type="button" name="button" id="button">2</button>
<button type="button" name="button" id="button">3</button>
<button type="button" name="button" id="button">4</button>
<button type="button" name="button" id="button">5</button>
<button type="button" name="button" id="button">6</button>
<button type="button" name="button" id="button">7</button>
<button type="button" name="button" id="button">8</button>
<button type="button" name="button" id="button">9</button>
</div>
<div id="operators">
<button type="button" name="button" id="button">-</button>
<button type="button" name="button" id="button">/</button>
<button type="button" name="button" id="button">*</button>
<button type="button" name="button" id="button">+</button>
<button type="button" name="button" id="button">=</button>
</div>
<input type="text" id="output">
<script src="./script.js" charset="utf-8"></script>
</body>
Three things. First, global variables - which in this case just means in a simple html/js page how to reference the same variables in different functions. Just define a variable outside of the function scope and it will be available to other functions on that page
let myVal;
function thing() {
myVal = 5;
}
function otherThing(){
console.log(myVal);
}
thing();
otherThing(); // shows in the console as 5
Second, your HTML needs some love. Setting everything with the same ID and the same name will cause problems for you. With this project, you don't actually need either of those because you're working from the actual button text (either a number or a math operator). So you can do away with all that.
<body>
<button type="button" name="button" id="clear">Clear</button>
<div id="buttons">
<button type="button">1</button>
<button type="button">2</button>
<button type="button">3</button>
<button type="button">4</button>
<button type="button">5</button>
<button type="button">6</button>
<button type="button">7</button>
<button type="button">8</button>
<button type="button">9</button>
</div>
<div id="operators">
<button type="button">-</button>
<button type="button">/</button>
<button type="button">*</button>
<button type="button">+</button>
<button type="button">=</button>
</div>
<input type="text" id="output">
<script src="./script.js" charset="utf-8"></script>
</body>
Third, in your function, it's getting a number value from the input, but it's coming in as a string, and if you try to just add that to something, it will concatenate it instead. Convert it to a number:
function selector(event) {
let target = event.target;
if (target.matches('button')) {
let value = target.innerHTML
// any of these will work:
// value = parseInt(value); // assuming there are no decimal points
// value = +value
// value = Number(value);
// same goes for the other, so you can rewrite this like:
let result = +document.querySelector('#output').value + +value
// or
// let result = Number(document.querySelector('#output').value) + Number(value)
}}
/* BEGIN SCRIPT.JS FILE */
var select = document.querySelector('#buttons')
var operating = document.querySelector('#operators')
select.addEventListener('click', selector)
operating.addEventListener('click', operatorSign)
let result;
function selector_OLD(event) {
let target = event.target;
if (target.matches('button')) {
let value = target.innerHTML
let result = document.querySelector('#output').value += value
}
}
function selector(event) {
let target = event.target;
if (target.matches('button')) {
let value = target.innerHTML
// any of these will work:
// value = parseInt(value); // assuming there are no decimal points
// value = +value
// value = Number(value);
// same goes for the other, so you can rewrite this like:
let result = +document.querySelector('#output').value + +value
// or
// let result = Number(document.querySelector('#output').value) + Number(value)
}
}
function operatorSign(e) {
let operator = e.target;
if (operator.matches('button')) {
let value = operator.innerHTML
if (value === "+") {
return add(a, b)
} else if (value === "-") {
return subtract(a, b)
} else if (value === "*") {
return multiply(a, b)
} else if (value === "/") {
return divide(a, b)
} else {
return null
}
}
}
/* END SCRIPT.JS FILE */
<button type="button" name="button" id="clear">Clear</button>
<div id="buttons">
<button type="button">1</button>
<button type="button">2</button>
<button type="button">3</button>
<button type="button">4</button>
<button type="button">5</button>
<button type="button">6</button>
<button type="button">7</button>
<button type="button">8</button>
<button type="button">9</button>
</div>
<div id="operators">
<button type="button">-</button>
<button type="button">/</button>
<button type="button">*</button>
<button type="button">+</button>
<button type="button">=</button>
</div>
<input type="text" id="output">
i am trying to save the value of calculator's tab when you reload the page and set the button to save and put value in calculator ( sry for broken english ).
I just can not link the calculator's tab and cookies.
> <!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-cookies.js"></script>
</head>
<body ng-controller="kyk">
<p>{{ $cookies.get('cookie') }}</p>
<input type="text" ng-model="cookieVal">
<button ng-click="setCookie(cookieVal)">update</button>
<div ng-controller="CalculatorController">
<br> <span id="myFavorite" >{{formula.join('')}}</span> <br><br><br>
<button ng-click="add(7)">7</button>
<button ng-click="add(8)">8</button>
<button ng-click="add(9)">9</button>
<button ng-click="add('/')">/</button><br>
<button ng-click="add(4)">4</button>
<button ng-click="add(5)">5</button>
<button ng-click="add(6)">6</button>
<button ng-click="add('*')">*</button><br>
<button ng-click="add(1)">1</button>
<button ng-click="add(2)">2</button>
<button ng-click="add(3)">3</button>
<button ng-click="add('-')">-</button><br>
<button ng-click="add(0)">0</button>
<button ng-click="add('.')">.</button>
<button ng-click="add('+')">+</button>
<button ng-click="eval()">=</button> <br>
<button ng-click="remove()">CLEAR</button>
<button ng-click="save">SAVE</button>
<button ng-click="put(formula.join(''))">PUT</button>
</div>
</body>
</html>
app = angular.module('app',['ngCookies',])
app.controller('kyk', function ($scope, $cookies) {
$scope.$cookies = $cookies;
$scope.myCookieVal = $cookies.get('cookie');
$scope.setCookie = function (val) {
$cookies.put('cookie', val);
};
});
app.controller('CalculatorController', function ($scope, $cookies) {
$scope.$cookies = $cookies;
$scope.formula = [0];
$scope.add = function (item) {
if($scope.formula == 0) $scope.formula = [item];
else $scope.formula.push(item);
};
$scope.remove = function () {
$scope.formula.pop();
if($scope.formula = ['']) $scope.formula = [0];
};
$scope.eval = function () {
var result = eval($scope.formula.join(''));
$scope.formula = [result];
$cookies.get('formul', $scope.formula.join(''));
$cookies.put('formul', )
};
$scope.save = function() {
$cookies.getObject('save');
};
$scope.put = function (value) {
$cookies.putObject('save', value);
if($scope.formula == 0) $cookies.putObject ('save', value);
else $scope.formula.push($cookies.putObject('save', value));
}
});
I am completely new to the Javascript .When I am looking to get the value to the button its get failed.I already given the setEvent.Like getEle();
And also bind the click function, Now i want to get the input values and perform mathematical calculations.
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
<link rel="stylesheet" type="text/css" href="calculator.css">
</head>
<body>
<div id="container" >
<div class="calculator">
<ul>
<li>
<div id="display">
<span id="math"></span>
<span id="number"></span>
</div>
</li>
<li>
<button class="input" value="7">7</button>
<button class="input" value="8">8</button>
<button class="input" value="9">9</button>
<button class="control" value="/">÷</button>
<button class="undo" value="-1">←</button>
</li>
<li>
<button class="input" value="4">4</button>
<button class="input" value="5">5</button>
<button class="input" value="6">6</button>
<button class="control" value="*">×</button>
<button class="clear">C</button>
</li>
<li>
<button class="input" value="1">1</button>
<button class="input" value="2">2</button>
<button class="input" value="3">3</button>
<button class="control" value="-">-</button>
<button class="control" value="%">%</button>
</li>
<li>
<button class="input size2" value="0">0</button>
<button class="input" value=".">∙</button>
<button class="control" value="+">+</button>
<button class="submit">=</button>
</li>
</ul>
</div>
</div>
</body>
<script type="text/javascript" src="calculator.js"></script>
</html>
javascript
function setEvent(evt, ele, callback) {
var ele = getEle(ele);
if (ele.length === undefined) {
ele.addEventListener(evt, callback, false);
} else if(ele.length > 0) {
for (var i=0; i<ele.length; i++) {
ele[i].addEventListener(evt, callback, false);
}
}
return false;
}
function getEle(ele) {
var _idf = ele.charAt(0);
if (_idf == "#") {
var _ele = document.getElementById(ele.substr(1));
return _ele;
} else if(_idf == ".") {
var _els = document.getElementsByClassName(ele.substr(1));
return _els;
}
return ele;
}
setEvent("click", ".input", function() {
console.log(this.value);
});
setEvent("click", ".control", function() {
console.log(this.value);
});
function setEvent(evt, ele, callback) {
var ele = getEle(ele);
if (ele.length === undefined) {
ele.addEventListener(evt, callback, false);
} else if(ele.length > 0) {
for (var i=0; i<ele.length; i++) {
ele[i].addEventListener(evt, callback, false);
}
}
return false;
}
function getEle(ele) {
var _idf = ele.charAt(0);
if (_idf == "#") {
var _ele = document.getElementById(ele.substr(1));
return _ele;
} else if(_idf == ".") {
var _els = document.getElementsByClassName(ele.substr(1));
return _els;
}
return ele;
}
function getInnerHtml(id) {
return document.getElementById(id).innerHTML;
}
function getValue(elem) {
return elem.value;
}
setEvent("click", ".input", function() {
console.log(this.value);
var _num = getInnerHtml("number");
_num = _num + "" + getValue(this);
document.getElementById("number").innerHTML = _num;
});
setEvent("click", ".control", function() {
console.log(this.value);
var _num1 = document.getElementById("number").innerHTML;
_num1 = _num1 + "" + this.value;
document.getElementById("number").innerHTML = _num1;
});
setEvent("click", ".clear", function() {
console.log(this.value);
var _num1 = document.getElementById("number").innerHTML;
_num1 = "";
document.getElementById("number").innerHTML = _num1;
});
setEvent("click", ".submit", function() {
console.log(this.value);
var _num1 = document.getElementById("number").innerHTML;
_num1 = eval( _num1 + "" + getValue(this));
document.getElementById("number").innerHTML = _num1;
});
Hope this will work out.
You can print the values to the screen by using document.getElementById("number").innerHTML = this.value.
Notie that it is not jquery, when calling getElementById you don't do("#id") only ("id"), JavaScript will match the string with the desired Id.
In jquery, it is much like the behavior of css, so in order to find ID you don't do getElementById instead, you just do
//$ means jquery
$("#id")
which is equivalent to java script's getElementById.
This JS program should return function ggt(x,z). I tried to implement it this way, everything is ok except this part I believe: document.getElementById("demo").innerHTML=ggt(x,z);
What should be added to make this function work properly? Thanks
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function calculate(){
var a=document.getElementById("in1").value;
var b=document.getElementById("in2").value;
if(isNaN(a) || isNaN(b)){
alert("Not a number");
}else{
ggt(a,b);
}
}
function ggt(x,y){
if (y==0){
return x;
}else{
var z=x%y;
document.getElementById("demo").innerHTML=ggt(x,z);
return ggt(x,z);
}
}
</script>
<div>
<input id="in1" type="text" />
<input id="in2" type="text" />
<input type="button" onclick="calculate()" value="compute" />
<p id="demo"></p>
</div>
</body>
</html>
function calculate()
{
var a = document.getElementById("in1").value;
var b = document.getElementById("in2").value;
if (isNaN(a) || isNaN(b)) {
alert("Not a number");
} else {
var values = ggt(a, b);
console.log(values);
if (values.valid) {
document.getElementById("demonumber").innerHTML = values.number;
document.getElementById("demomodulus").innerHTML = values.modulo;
}
}
}
function ggt(x, y) {
var res = {};
if (y == 0) {
res.valid = false;
} else {
res.valid = true;
res.number = x;
res.modulo = x % y;
}
return res
}
<div>
<input id="in1" type="text" />
<input id="in2" type="text" />
<input type="button" onclick="calculate()" value="compute" />
<p id="demonumber"></p>
<p id="demomodulus"></p>
</div>