clearing the display in a javascript calculator after pressing "=" - javascript

I'm new to coding and I built a Javascript calculator, but I can't get the display to clear after Im done with one calculation. Instead, the result of the first calculation goes into the input for the second calculation. For eg if I do 3+5 it'll give me 8, but if I then press 4, the display says 84 which is why its a problem. I can clear the screen via the clear button but it gets tedious after every single calculation. Thank you.
//select all the buttons
const buttons = document.querySelectorAll('button');
//select the <input type="text" class+"display" disabled> element
const display = document.querySelector('.display');
//add eventListener to each button
buttons.forEach(function(button) {
button.addEventListener('click',calculate);
});
//calculate function
function calculate(event) {
//current clicked buttons value
var clickedButtonValue = event.target.value;
if(clickedButtonValue === '=') {
//check if the display is not empty then only do the calculation
if(display.value !== "") {
//calculate and show the answer to display
display.value = eval(display.value);
}
//if any key except "=" pressed again clear display
button.addEventListener('click',clearDisplay);
} else if (clickedButtonValue === 'C') {
//clear everything on display
display.value = "";
} else {
//otherwise concatenate it to the display
display.value += clickedButtonValue;
}
}
function clearDisplay(clickedButtonValue) {
if(clickedButtonValue !== "=") {
display.value = "";
}
}

You can have a variable that keeps track of the calculated state. If it has been calculated, clear the display and reset the state
var calculated = false;
function calculate( event ){
var clickedButtonValue = event.target.value;
if ( calculated ) {
display.value = "";
calculated = false;
}
if(clickedButtonValue === '=') {
if(display.value !== "") {
//calculate and show the answer to display
display.value = eval(display.value);
calculated = true;
}
}
// the rest of your logic here
}

Related

Button dissapear when value reaches 0 JAVASCRIPT

This my code:
$('.upgrade-strength').on('click', function () {
var strCount = $('#strId');
var points = $('#points');
var userId = $(this).attr('id');
strCount.html(function(i, val) { return val*1+1 });
points.html(function(i, val) {
if(val*1>0){
return val*1-1;
}else{
document.getElementById("strBtn").innerHTML = "";
document.getElementById("dexBtn").innerHTML = "";
document.getElementById("vitBtn").innerHTML = "";
document.getElementById("intBtn").innerHTML = "";
}
});
$.ajax("/upgrade-strength/"+userId,
{
});
});
<p>Available points: <strong><span id="points">{{Auth::user()->points}}</span></strong></p>
When I clicking the button the counter goes down till 0 and then button dissapears. But what happens more is, when the
points.html(function(i, val) reaches zero the button did not dissapear. You have to click one more time tu buttons dissapear. How to solve this ?
Try this it will work:
strCount.html(function(i, val) { return val*1+1 });
points.html(function(i, val) {
if(val*1>0){
val = val*1-1;
if(val == 0){
document.getElementById("strBtn").innerHTML = "";
document.getElementById("dexBtn").innerHTML = "";
document.getElementById("vitBtn").innerHTML = "";
document.getElementById("intBtn").innerHTML = "";
}
return val;
}else{
document.getElementById("strBtn").innerHTML = "";
document.getElementById("dexBtn").innerHTML = "";
document.getElementById("vitBtn").innerHTML = "";
document.getElementById("intBtn").innerHTML = "";
}
When val is 1, look at your code, and see what it's doing:
if(val*1>0) - I don't know why you keep using *1 but never mind that. 1 > 0 is true, so we're in the if block.
return val*1-1; - again, what's the deal with *1? Anyway, this returns 0.
The else block is not run.
The next time you click, if(val*1>0) is false so the else gets run, hiding the buttons.
Instead you should do something like:
If the value is 1, hide the buttons
Either way, return val-1;

javascript calulator display: output displaying computed calculation with "=" sign instead of just computed value

var buttons = document.querySelectorAll('.btn');
var display = document.getElementById('display');
buttons.forEach(function (element, index) {
element.addEventListener('click', addToScreen, answer);
});
function addToScreen() {
var val = this.getAttribute('value');
if (val == '=') {
answer();
}
console.log(val);
display.value += val;
}
function answer() {
val = display.value;
val = eval(val);
display.value = "";
display.value += val;
}
Hi All,
so these are my two functions that display and compute the calculation for the calculator.
however there are a couple of problems I am running. the first is that when a calculation is performed the out is a number with an equal sign for eg. 8*8 the display would be 64=. how can I get rid of the "=" sign.
second problem is with my ifval=='=' statement. The statement causes the program to jump to the answer function which has eval(val) statement. however if a user enters "=" as the first input/second this would display undefined on the display calculator screen. how can I fix these two issues?
Thanks
Return after you call answer() inside the addToScreen function
function addToScreen() {
var val = this.getAttribute('value');
if (val == '=') {
answer();
return;
}
console.log(val);
display.value += val;
}

updated values inside form do not transfer properly into new div

basically when you enter a value out of the specified range it gets updated to the minimum/maximum allowed, but the value of the var doesn't get updated to the max/min. (you can check by entering 1 into both forms and clicking on quote)
https://jsfiddle.net/epf4uyr6/
function cadCheck(input) {
if (input.value < 2) input.value = 2;
if (input.value >= 100) input.value = 99.99;
}
document.getElementById('cad').onkeyup = function() {
var cad = (this.value);
document.getElementById("cad-quote").innerHTML = "Market: $" +cad;
}
your values not updating properly because , keyup function executing first and then onchange(cadCheck) function execute.
your current logic is inside onchange function , thats why value not updating properly.
move this line in onkeyup function , and remove it from onchange.
document.getElementById('cad').onkeyup = function() {
if (this.value >= 100) this.value = 99.99;
var cad = (this.value);
document.getElementById("cad-quote").innerHTML = "Market: $" +cad;
}

How to force loop to wait until user press submit button?

I have simple function which checks if entered pin code is valid. But i don't know how to force for-loop to wait until i enter code again to check again it's validity.
So how it should be - i type PIN code, then click OK button and it checks whether it's correct (if it is, i can see my account menu; if it's not i have to type it again and i have 2 chances left). My code fails, because PIN when code is wrong program should wait until i type new code and press OK button again.
I tried setTimeout(), callback(), but it doesn't work. This is what i have - a function with for-loop that just runs 3 times (as it is suppose to, but not instantly) without giving a chance to correct the PIN code.
That's whole, unfinished yet, code: http://jsfiddle.net/j1yz0zuj/
Only function with for-loop, which checks validity of PIN code:
var submitKey = function(callback)
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
for (i=0; i<3; i++)
{
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (2-i);
callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
if (i=2) console.log("blokada");
}
}
else if (digitStatus == 1)
{
}
}
Your approach is wrong. You should not make the user wait!!! You need 2 more variables at the top of your programm pincount=0 and pininputallowed. Increase pincount in the submit key function by 1 and then check if pincount<3.
Here is a corrected version of your code.
http://jsfiddle.net/kvsx0kkx/16/
var pinCount=0,
pinAllowed=true;
var submitKey = function()
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
pinCount++;
if(pinCount >= 3) {
pinAllowed = false;
onScreen.innerHTML = "<br>blokada";
}
if(pinAllowed){
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (3-pinCount);
inputLength = 0;
document.getElementById("screen").innerHTML += "<br>Wpisz kod PIN: ";
//callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
}
}
else if (digitStatus == 1)
{
}
}
You need to create much more variables to control your machine. Your add/delete digit function had conditions that were badly written and only worked if the text on the screen was short enough.
var inputLength = 0;
addDigit = function(digit){
//numKeyValue = numKeyValue instanceof MouseEvent ? this.value : numKeyValue;{
if (inputLength < pinLength) {
onScreen.innerHTML += this.value;
inputLength++;
}
//if (onScreen.innerHTML == 1234) console.log("PIN został wprowadzony");
},
delDigit = function(){
if (inputLength >= 0) {
onScreen.innerHTML = onScreen.innerHTML.slice(0, -1);
inputLength--;
}
};
If you want to empty the screen at any moment you can insert onScreen.innerHTML = ''; anywhere
ps: Thanks for the exercise and nice automat you made there.

Lost part of page after post page

After clicking start in this page, the value is lost.
What can I do, in order not to make the page reload itself?
<button onclick="start()">Start</button>
Start: this is called when the user clicks start on the setup screen
function start(reuse){
reuse = (typeof reuse === 'undefined') ? false : true;
//user input is read
numberOfQuestions = $("#amount").val();
time = $("#time").val();
showError = $("#showError").prop("checked");
showCorrect = $("#showCorrect").prop("checked");
fullscreen = $("#fullscreen").prop("checked");
//currentIndex is the index of current question in the list while in the quiz
currentIndex = -1;
//reset correct questions
correct = 0;
var pred = {place:1, time:2, other:3};
var _numberOfQuestions = 0;
if (reuse){
_data = filteredData;
} else {
_data = data;
}
//filteredData is the new list of question AFTER filtering it according to setup screen
filteredData = [];
$.each(_shuffle(_data), function(index, entry){
if ($("#ddcl-d1-i"+entry['pad']).prop("checked")){
if ($("#ddcl-d2-i"+pred[entry['pred']]).prop("checked")){
_numberOfQuestions++;
entry['a'] = _shuffle(entry['a']);
filteredData.push(entry);
}
}
if (_numberOfQuestions == numberOfQuestions) return false;
});
if (_numberOfQuestions == 0){
alert("No questions available");
return;
}
$("#quiz").show();
$("#setup").hide();
$("#finish").hide();
secondsLeft = time * numberOfQuestions;
doTimer();
nextQuestion();
if (fullscreen && screenfull.enabled){
screenfull.request(document.getElementById('container'));
}
}
I call Start with JavaScript.
I try to add autopostback ="false", but the outcome remains the same.
You can add type attribute to buttons, because they automatically submit forms.
<button type="button" onclick="start()">Start</button>

Categories