How to get Number input on screen javascript - javascript

Im trying to get my numbers to display the assigned value on screen but I have no clue how to do it.
<div class="container">
<div class="Calaculatorout">
<div class="calculatordisplay">0</div>
<div class="buttons">
<button class="nine">9</button>
<button class="eight">8</button>
<button class="seven">7</button>
<button class="six">6</button>
<button class="five">5</button>
<button class="four">4</button>
<button class="three">3</button>
<button class="two">2</button>
<button class="one">1</button>
<button class="zero">0</button>
<button class="multi">X</button>
<button class="divide">/</button>
<button class="plus">+</button>
<button class="minus">-</button>
<button class="myForm">AC</button>
</div>
</div>
</div>
I need to find a way to assign the values in js or for them to appear on the webpage.
const del = document.querySelector(".back");
const buttons = document.querySelectorAll(".buttons");
const clear = document.querySelector(".clear");
const display = document.querySelector(".calculatordisplay");
buttons.forEach((button) => {
buttons.addEventListener("click", (e) => {
appendNumber(e);
updateDisplay();
});
});
function updateDisplay() {
display.textcontent;
}

Please be more specific with the question and provide all the details.
Anyway, the below code will help you to display the button value on the screen. Also, I added the concatenation logic.
But if you are trying to implement a calculator you need to do an extra bit of logic. Don't forget to handle number/0 or 0/0 scenario 😉
var disp = '';
function myFunction(x) {
disp = disp + x;
if(x == "AC") {
document.getElementById("calculatordisplay").innerHTML = 0;
} else if(disp == "") {
document.getElementById("calculatordisplay").innerHTML = x;
} else {
document.getElementById("calculatordisplay").innerHTML = disp;
}
}
<div class="container">
<div class="Calaculatorout">
<div id="calculatordisplay">0</div>
<div id="buttons">
<button onclick="myFunction(value)" id="nine" value="9">9</button>
<button onclick="myFunction(value)" id="eight" value="8">8</button>
<button onclick="myFunction(value)" id="seven" value="7">7</button>
<button onclick="myFunction(value)" id="six" value="6">6</button>
<button onclick="myFunction(value)" id="five" value="5">5</button>
<button onclick="myFunction(value)" id="four" value="4">4</button>
<button onclick="myFunction(value)" id="three" value="3">3</button>
<button onclick="myFunction(value)" id="two" value="2">2</button>
<button onclick="myFunction(value)" id="one" value="1">1</button>
<button onclick="myFunction(value)" id="zero" value="0">0</button>
<button onclick="myFunction(value)" id="multi" value="X">X</button>
<button onclick="myFunction(value)" id="divide" value="/">/</button>
<button onclick="myFunction(value)" id="plus" value="+">+</button>
<button onclick="myFunction(value)" id="minus" value="-">-</button>
<button onclick="myFunction(value)" id="myForm" value="AC">AC</button>
</div>
</div>
</div>

Related

Is the eval() function the ideal approach to carry out calculations?

I have trying to create a calculator using the eval() function. But for some reason my numbers and operator buttons wont show on the screen(form). Below is my html and js code.
const btns = document.querySelectorAll('.btn');
var screenView = document.querySelector('.screen');
const equalBtn = document.querySelector('.btn-equal');
const clearBtn = document.querySelector('.btn-clear');
for (let i = 0; i < btns.lenght; i++) {
btns[i].addEventListener('click', function() {
let number = btns[i].getAttribute('data-num');
screenView.value += number;
})
}
equalBtn.addEventListener('click', function() {
let value = eval(screenView.value);
screenView.value = value;
})
clearBtn.addEventListener('click', function() {
screenView.value = '';
})
<section class="calculator">
<form>
<input type="text" name="" id="" class="screen">
</form>
<div class="buttons">
<button type="button" class="btn btn-digits" data-num="7">7</button>
<button type="button" class="btn btn-digits" data-num="8">8</button>
<button type="button" class="btn btn-digits" data-num="9">9</button>
<button type="button" class="btn btn-operators" data-num="/">/</button>
<button type="button" class="btn btn-digits" data-num="4">4</button>
<button type="button" class="btn btn-digits" data-num="5">5</button>
<button type="button" class="btn btn-digits" data-num="6">6</button>
<button type="button" class="btn btn-operators" data-num="*">*</button>
<button type="button" class="btn btn-digits" data-num="1">1</button>
<button type="button" class="btn btn-digits" data-num="2">2</button>
<button type="button" class="btn btn-digits" data-num="3">3</button>
<button type="button" class="btn btn-operators" data-num="-">-</button>
<button type="button" class="btn btn-digits" data-num=".">.</button>
<button type="button" class="btn btn-digits" data-num="0">0</button>
<button type="button" class="btn-clear btn-digits">C</button>
<button type="button" class="btn btn-operators" data-num="+">+</button>
<button type="button" class="btn-equal btn-digits">=</button>
</div>
</section>
You have a typo there: lenght instead of length.
Also, I feel obliged to say, that eval() should always be considered after everything
else failed, as the last resort.

How can I select select a key when shifted

When I try to click on the keyboard keys like this: "/", (that requieres shift) it doesn't execute the code it is supposed to...I can't select it. Should I find another way? the complete code of my exercise is here: https://repl.it/#Sesadada/CALCULATOR
const buttons = document.querySelectorAll("button");
window.addEventListener("keydown", (e) => {
const key = document.querySelector(`button[data-key='${e.which}']`);
console.log(e.which, e.shiftKey);
if (e.which == 13) {
equal.click();
} else if (e.which == 8) {
zero();
} else {
key.click();
}
});
<div class="nums">
<button type="button" class="operator" data-key="80" value="%">%</button>
<button type="button" class="operator" data-key="68" value="/">/</button>
<button type="button" class="operator" data-key="187" value="+">+</button>
<button type="button" class="operator" data-key="88" value="*">x</button>
<button type="button" class="operator" data-key="189" value="-">-</button>
<button id="zero" type="button" class="operand" data-key="48" value="0">0</button>
<button type="button" class="equal" data-key="48" value="=">=</button>
</div>
You can use e.key to get the actual character that is being passed. So when the user holds shift + 5, e.key equals %.
const buttons = document.querySelectorAll(".operator");
buttons.forEach(function(e) {
e.addEventListener("click", function(el) {
console.log(el.target.value + " clicked");
});
});
window.addEventListener("keydown", (e) => {
const key = document.querySelector(`button[value='${e.key}']`);
if (key) {
key.click();
} else if (e.which == 13) {
equal.click();
} else if (e.which == 8) {
zero();
}
//const divide = document.querySelector(
//`button[data-key='${e.which.shiftKey}']`
//equal.click();
});
<div class="nums">
<button type="button" class="operator" data-key="5" value="%">%</button>
<button type="button" class="operator" data-key="68" value="/">/</button>
<button type="button" class="operator" data-key="187" value="+">+</button>
<button type="button" class="operator" data-key="88" value="*">x</button>
<button type="button" class="operator" data-key="189" value="-">-</button>
<button id="zero" type="button" class="operand" data-key="48" value="0">0</button>
<button type="button" class="equal" data-key="48" value="=">=</button>
</div>

If first input is focused write there else to second one

How can I make for example If first input .res is focused write there else on .res2 I tried this firstly .res is focused then when you click buttons which are into .operators div focus moves to second input .res2 but it doesnt work
$(".one,.two,.three,.four,.five,.six,.seven,.eight,.nine,.zero,.dot").click(function(){
if($('.res').is(":focus")){
firstNumber = $('.res').val(($('.res').val()) + $(this).val());
} else {
secondNumber = $('.res2').val(($('.res2').val()) + $(this).val());
}
})
$(".plus,.subtract,.divide,.multiply").click(function(){
resultWindow.blur();
$('.res2').focus();
})
<div id="calculator">
<div class="wind">
<input class="res" value=" " maxlength="24">
<input class="res2" value=" " maxlength="24">
<div class="numbers">
<button class="one" value="1">1</button>
<button class="two" value="2">2</button>
<button class="three" value="3">3</button>
<br>
<button class="four" value="4">4</button>
<button class="five" value="5">5</button>
<button class="six" value="6">6</button>
<br>
<button class="seven" value="7">7</button>
<button class="eight" value="8">8</button>
<button class="nine" value="9">9</button>
<br>
<button class="zero" value="0">0</button>
<button class="dot" value=".">.</button>
</div>
<div class="operators">
<button class="plus">+</button>
<button class="subtract">-</button>
<button class="divide">/</button>
<button class="multiply">*</button>
<button class="equal">=</button>
</div>
</div>
The main issue is that every time you click the button, the input blurs and the button gains focus.
So, $('.res').is(":focus") will always return false.
To achieve this, you need to add another event listener to prevent the default behavior of the button clicks:
$("button").mousedown(function(e) {e.preventDefault()})
Also, I'd recommend to use this query selector:
$(".numbers > button")
$(".operators > button")
So, your code looks simpler.
Take a look how it works:
$("button").mousedown(function(e) {e.preventDefault()})
$(".numbers > button").click(function() {
if ($('.res').is(":focus")) {
firstNumber = $('.res').val(($('.res').val()) + $(this).val());
} else {
secondNumber = $('.res2').val(($('.res2').val()) + $(this).val());
}
})
$(".operators > button").click(function() {
resultWindow.blur();
$('.res2').focus();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="calculator">
<div class="wind">
<input class="res" value=" " maxlength="24">
<input class="res2" value=" " maxlength="24">
<div class="numbers">
<button class="one" value="1">1</button>
<button class="two" value="2">2</button>
<button class="three" value="3">3</button>
<br>
<button class="four" value="4">4</button>
<button class="five" value="5">5</button>
<button class="six" value="6">6</button>
<br>
<button class="seven" value="7">7</button>
<button class="eight" value="8">8</button>
<button class="nine" value="9">9</button>
<br>
<button class="zero" value="0">0</button>
<button class="dot" value=".">.</button>
</div>
<div class="operators">
<button class="plus">+</button>
<button class="subtract">-</button>
<button class="divide">/</button>
<button class="multiply">*</button>
<button class="equal">=</button>
</div>
</div>
Try doing a mousedown event instead of a click event on your buttons, and then preventing default, which should keep the input from losing focus.
$(".one,.two,.three,.four,.five,.six,.seven,.eight,.nine,.zero,.dot").on('mousedown', function(event){
event.preventDefault();
if($('.res').is(":focus")){...}
...
});

How can I push selected buttons name and value into javascript multidimensional array?

I have some buttongroups like this:
<div class="btn-group" id="RPPP">
<button type="button" class="btn" name="PPP" value="1">1</button>
<button type="button" class="btn" name="PPP" value="2">2</button>
<button type="button" class="btn" name="PPP" value="3">3</button>
<button type="button" class="btn" name="PPP" value="4">4</button>
<button type="button" class="btn" name="PPP" value="5">5</button>
</div>
...and at the bottom an "Analyse" button.
<a href="#last" id="secnext" class=" btn-lg btn-info " >Analyse</a>
they look like this
In the eventlistener function i'd like to push the selected button's name and value into an multidimensional array.
var myBtnn = document.getElementById('secnext');
myBtnn.addEventListener('click', function(event) {
var array =[];
//store buttons name and value both in an array
}
So that I'll have them like:
[PPP][4]
[TTT][3]
[DDD][5]
Take a look at this sample code.
You need Array#reduce and forin to achieve what you want.
Note that I am selecting all the buttons with this call:
Also, note that I have put all buttons in one group, but I hope you get the idea.
var coll = document.querySelectorAll('button');
So, depending on your html you may want to change the html to select the buttons.
var myBtnn = document.getElementById('secnext');
myBtnn.addEventListener('click', function (event) {
var array = [];
var coll = document.querySelectorAll('button');
//store buttons name and value both in an array
var collArr = [].slice.call(coll);
var ans = [];
var obj = collArr.reduce(function (obj, btn) {
if (!obj[btn.name]) {
obj[btn.name] = 0;
}
obj[btn.name]++;
return obj;
}, {});
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
ans.push([i, obj[i]]);
}
}
console.log(ans);
});
<div class="btn-group" id="RPPP">
<button type="button" class="btn" name="PPP" value="1">1</button>
<button type="button" class="btn" name="PPP" value="2">2</button>
<button type="button" class="btn" name="PPP" value="3">3</button>
<button type="button" class="btn" name="PPP" value="4">4</button>
<button type="button" class="btn" name="TTT" value="1">1</button>
<button type="button" class="btn" name="TTT" value="2">2</button>
<button type="button" class="btn" name="TTT" value="3">3</button>
<button type="button" class="btn" name="DDD" value="4">4</button>
<button type="button" class="btn" name="DDD" value="5">5</button>
<button type="button" class="btn" name="DDD" value="4">6</button>
<button type="button" class="btn" name="DDD" value="5">7</button>
<button type="button" class="btn" name="DDD" value="5">8</button>
</div>
Analyse
You should use objects instead of arrays.
So if you have an object like PPP you can put an array inside the object.
Example:
var obj = {
'PPP' : ['1', '2'],
'TTT' : ['1', '2']
};
obj.PPP[0] == '1';
obj.PPP[1] == '2';
obj.TTT[0] == '1';
obj.TTT[1] == '2';

Javascript calculator issues

I have to following code:
<div class="overall">
<div class="calccont">
<input type="text" class="output">
</div>
<div class="buttons">
<button class="btn" type="button" value="1">1</button>
<button class="btn" type="button" value="2">2</button>
<button class="btn" type="button" value="3">3</button>
<button class="btn" type="button" value="4">4</button>
</div>
</div>
and
var allBtns = document.querySelectorAll(".btn");
for ( i = 0; i < allBtns.length; i++ ) {
allBtns[i].addEventListener("click", function(){
document.querySelector(".output").value += allBtns[i].getAttribute("value");
});
}
Im trying to build a calculator in JS and the expected result was putting all the buttons value in the input, but it doesnt seem to work. Any help will be greatly appreciated.
You should be using this to access the current button within your click event:
var allBtns = document.querySelectorAll(".btn");
for (i = 0; i < allBtns.length; i++) {
allBtns[i].addEventListener("click", function() {
document.querySelector(".output").value += this.getAttribute("value");
});
}
<div class="overall">
<div class="calccont">
<input type="text" class="output">
</div>
<div class="buttons">
<button class="btn" type="button" value="1">1</button>
<button class="btn" type="button" value="2">2</button>
<button class="btn" type="button" value="3">3</button>
<button class="btn" type="button" value="4">4</button>
<div>
You should use the this keyword to access the clicked button and then get its value like this:
var allBtns = document.querySelectorAll(".btn");
for ( i = 0; i < allBtns.length; i++ ) {
allBtns[i].addEventListener("click", function(){
document.querySelector(".output").value += this.getAttribute("value");
});
}
<div class="overall">
<div class="calccont">
<input type="text" class="output">
</div>
<div class="buttons">
<button class="btn" type="button" value="1">1</button>
<button class="btn" type="button" value="2">2</button>
<button class="btn" type="button" value="3">3</button>
<button class="btn" type="button" value="4">4</button>
<div>
More about the this keyword:
In most cases, the value of this is determined by how a function is
called. It can't be set by assignment during execution, and it may be
different each time the function is called. ES5 introduced the bind
method to set the value of a function's this regardless of how it's
called, and ECMAScript 2015 introduced arrow functions whose this is
lexically scoped (it is set to the this value of the enclosing
execution context).
On a side note: You are missing a < in the first div tag in the code you have posted, that might also be causing you some issues if that wasn't a copy-paste omission.

Categories

Resources