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>
Related
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 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.
Ive got HTML code with a button group and a submit button. The script code checks if it is selected or not and submits based on that selection. If none of the buttons are selected, then display the alert.
$("#Save").on("click", Save);
function Save(e) {
if (GeneralStatusAlert(e) == false) {
return;
} else {
$('#frmSubmit').submit();
}
}
function GetGeneralStatus() {
var value = "";
var row = $("#btnGeneral").closest(".row")
var object = $(this).find(".btn-group");
value = $(object).find(".selected");
return value;
}
function GeneralStatusAlert(e) {
var value = GetGeneralStatus();
if (value.length < 1) {
alert("Please set Status.");
return false;
}
return true;
}
$('.testRow button').click(function () {
$(this).addClass("selected");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/css/bootstrap.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row testRow">
<div class="btn-group btnGeneral">
<button type="button" class="btn btn-success btnStatus" value="Open">Open</button>
<button type="button" class="btn btn-danger btnStatus" value="Closed">Closed</button>
</div>
</div>
<br/>
<br/>
<div class="row">
<button id="Save" class="btn btn-primary"><i class="fa fa-share-square-o"></i> Save</button>
</div>
It does not work. What am I missing?
EDIT : Added the select button class on button click.
I've updated your JS a little:
$("#Save").on("click", Save);
$(".btnStatus").on("click", function(){
$(".btnStatus").removeClass("selected");
$(this).addClass("selected");
});
function Save(e)
{
if (GeneralStatusAlert(e) == false) {
return;
}
else{
$('#frmSubmit').submit();
}
}
function GetGeneralStatus() {
var value = "";
value = $("div.btn-group").find(".selected");
return value;
}
function GeneralStatusAlert(e) {
var value = GetGeneralStatus();
if (value.length < 1) {
alert("Please set Status.");
return false;
}
return true;
}
Basically you weren't adding the selected class when clicking your status buttons. Also your code var object = $(this).find(".btn-group"); wasn't finding anything. (Due to using this)
There are few issues in your sample code
1: bootstrap.js is dependent on JQuery, so need to add that first.
2: Missing code to add selected class on status button
3: There is no element with id btnGeneral, you are using wrong selector. btnGeneral is a class and should be accessed by .
4: You may meant $(row) instead of $(this)
var row = $("#btnGeneral").closest(".row")
var object = $(this).find(".btn-group");
Updated sample code.
$("#Save").on("click", Save);
$(".btn").on("click", function(){
$(this).addClass("selected");
$(this).siblings().removeClass("selected");
});
function Save(e) {
if (GeneralStatusAlert(e) == false) {
return;
} else {
alert("Submitting");
$('#frmSubmit').submit();
}
}
function GetGeneralStatus() {
var value = "";
var row = $(".btnGeneral").closest(".row")
var object = $(row).find(".btn-group");
value = $(object).find(".selected");
return value;
}
function GeneralStatusAlert(e) {
var value = GetGeneralStatus();
if (value.length < 1) {
alert("Please set Status.");
return false;
}
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/css/bootstrap.css" rel="stylesheet"/>
<div class="row">
<div class="btn-group btnGeneral">
<button type="button" class="btn btn-success btnStatus" value="Open">Open</button>
<button type="button" class="btn btn-danger btnStatus" value="Closed">Closed</button>
</div>
</div>
<br/>
<br/>
<div class="row">
<button id="Save" class="btn btn-primary"><i class="fa fa-share-square-o"></i> Save</button>
</div>
I am looking for correct code so function named "finder()" can execute and find the highest value in Array named "sum" .
When press "Find max" button result is :"[object HTMLInputElement] "
Thank you for any help!
Here is code:
<html>
<head>
<title>Max</title>
<meta charset="utf-8">
<script type="text/javascript">
var sum = document.getElementsByName('addends');
function add() {
var x = document.getElementById('apendiks');
x.innerHTML+="<br/><input type='text' name='addends' size='7'>";
}
function finder() {
var max = sum[0];
for(i=0; i<sum.length;i++){
if(sum[i] > max){
max = sum[i];
}
}
document.getElementById('showMaxValue').innerHTML = max;
}
function gather() {
var total=0;
for(i=0; i < sum.length; i++){
total+=parseFloat(sum[i].value);
}
document.getElementById('score').innerHTML = total;
}
</script>
</head>
<body>
<p><input type="button" onclick="add()" value="Add a new box"> </p>
<p><input type="button" onclick="" value="-"> </p>
<div id="apendiks"></div>
<p><input type="button" onclick="gather()" value="Total sum"> </p>
<p>Score: <b id="score"></b></p>
<p><input type="button" onclick="finder()" value="Find max"> </p>
<p id="showMaxValue"></p>
</body>
</html>
var sum = document.getElementsByName('addends');
This line will give you a list of Nodes, not an Array.
In your finder method, you need to treat it as such
function finder()
{
var max = paeseInt(sum[0].value) ;
for(i=0; i<sum.length;i++){
if(parseInt(sum[i].value) > max && !isNaN(sum[i].value)){ //assuming that strings should be ignored
max = parseInt(sum[i].value) ;
}
}
document.getElementById('showMaxValue').innerHTML = max;
}
Use .value to get the value of input field
<html>
<head>
<title>Max</title>
<meta charset="utf-8">
<script type="text/javascript">
var sum = document.getElementsByName('addends');
function add() {
var x = document.getElementById('apendiks');
x.innerHTML+="<br/><input type='text' name='addends' size='7'>";
}
function finder() {
var max = sum[0].value;
for(i=0; i<sum.length;i++){
if(sum[i].value > max){
max = sum[i].value;
}
}
document.getElementById('showMaxValue').innerHTML = max;
}
function gather() {
var total=0;
for(i=0; i < sum.length; i++){
total+=parseFloat(sum[i].value);
}
document.getElementById('score').innerHTML = total;
}
</script>
</head>
<body>
<p><input type="button" onclick="add()" value="Add a new box"> </p>
<p><input type="button" onclick="" value="-"> </p>
<div id="apendiks"></div>
<p><input type="button" onclick="gather()" value="Total sum"> </p>
<p>Score: <b id="score"></b></p>
<p><input type="button" onclick="finder()" value="Find max"> </p>
<p id="showMaxValue"></p>
</body>
</html>
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.