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.
Related
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>
My current codes are not allowing me to properly display the operators. At this time I am not able to display an operator after an initial calculation. For example, if I do this '9+2' then press '='. I will get a result but if I press an operator like '*' the display will only show the operator without the number. Looking at my current code what am I missing? Please advise.
$(document).ready(function() {
var shouldbeClear = false;
//create variable to store input from user to calculate later
var inputs = [''];
//create string to store current input string
var totalString;
//create operators array for validation without the .
var operators1 = ['+', '-', '*', '/'];
var operators2 = ['.'];
//numbers for validation
var nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
function getValue(value) {
if (operators2.includes(inputs[inputs.length - 1]) === true && value === '.') {
alert('STOP & RESTART!!!');
} else if (inputs.length === 1 && operators1.includes(value) === false) {
inputs.push(value);
} else if (operators1.includes(inputs[inputs.length - 1]) === false) {
inputs.push(value);
} else if (nums.includes(Number(value))) {
inputs.push(value);
}
update();
}
function update() {
totalString = inputs.join('');
$('#display').html(totalString);
}
function getTotal() {
shouldbeClear = true;
totalString = inputs.join('');
$('#display').html(eval(totalString));
var result = document.getElementById("display").innerHTML;
inputs = [];
inputs[0] = '';
for (var i = 0; i <= result.length - 1; i++) {
inputs[i + 1] = result[i];
}
update();
}
$('button').on('click', function() {
if (this.id === 'deleteAll') {
inputs = ['0'];
update();
} else if (this.id === 'backSpace') {
inputs.pop();
update();
} else if (this.id === 'total') {
getTotal();
} else {
if (inputs[inputs.length - 1].indexOf('+', '-', '/', '*', '.') === -1) {
if (shouldBeCleared){
shouldBeCleared = false;
inputs=[''];
update();
getValue(this.id);
} else {
getValue(this.id);
}
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
<div id="calcOutput">
<span id="display">Enter Some Number...</span>
<hr>
</div>
<div class="text-center" id="calculator">
<button type="button" class="btn btn-danger btn-lg btn3d" id="deleteAll">AC</button>
<button type="button" class="btn btn-warning btn-lg btn3d" id="backSpace">CE</button>
<button type="button" class="btn btn-success btn-lg btn3d" id="/">/</button>
<button type="button" class="btn btn-success btn-lg btn3d" id="*">*</button><br>
<button type="button" class="btn btn-primary btn-lg btn3d" id="7">7</button>
<button type="button" class="btn btn-primary btn-lg btn3d" id="8">8</button>
<button type="button" class="btn btn-primary btn-lg btn3d" id="9">9</button>
<button type="button" class="btn btn-success btn-lg btn3d" id="-">-</button><br>
<button type="button" class="btn btn-primary btn-lg btn3d" id="4">4</button>
<button type="button" class="btn btn-primary btn-lg btn3d" id="5">5</button>
<button type="button" class="btn btn-primary btn-lg btn3d" id="6">6</button>
<button type="button" class="btn btn-success btn-lg btn3d" id="+">+</button><br>
<button type="button" class="btn btn-primary btn-lg btn3d" id="1">1</button>
<button type="button" class="btn btn-primary btn-lg btn3d" id="2">2</button>
<button type="button" class="btn btn-primary btn-lg btn3d" id="3">3</button>
<button type="button" class="btn btn-success btn-lg btn3d" id=".">.</button><br>
<button type="button" class="btn btn-info btn-lg btn3d bigButton" id="0">0</button>
<button type="button" class="btn btn-info btn-lg btn3d bigButton" id="total">=</button><br>
</div>
</div>
Add a variable which will inform the calculator whether it should clear everything.
I called the variable shouldBeCleared
Each time you click on = shouldBeCleared is set to true.
Then if you click on any NUMBER, check if shouldBeCleared is set to true, clear your inputs array and update().
As follows:
$(document).ready(function() {
var shouldBeCleared = false;
//create variable to store input from user to calculate later
var inputs = [''];
//create string to store current input string
var totalString;
//create operators array for validation without the .
var operators1 = ['+', '-', '*', '/'];
var operators2 = ['.'];
//numbers for validation
var nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
function getValue(value) {
if (operators2.includes(inputs[inputs.length - 1]) === true && value === '.') {
alert('STOP & RESTART!!!');
} else if (inputs.length === 1 && operators1.includes(value) === false) {
inputs.push(value);
} else if (operators1.includes(inputs[inputs.length - 1]) === false) {
inputs.push(value);
} else if (nums.includes(Number(value))) {
inputs.push(value);
}
update();
}
function update() {
totalString = inputs.join('');
$('#display').html(totalString);
}
function getTotal() {
shouldBeCleared = true;
totalString = inputs.join('');
$('#display').html(eval(totalString));
var result = document.getElementById("display").innerHTML;
inputs = [];
inputs[0] = '';
for (var i = 0; i <= result.length - 1; i++) {
inputs[i + 1] = result[i];
}
update();
}
$('button').on('click', function() {
if (this.id === 'deleteAll') {
inputs = ['0'];
update();
} else if (this.id === 'backSpace') {
inputs.pop();
update();
} else if (this.id === 'total') {
getTotal();
} else {
if (inputs[inputs.length - 1].indexOf('+', '-', '/', '*', '.') === -1) {
if (shouldBeCleared){
shouldBeCleared = false;
inputs=[''];
update();
}
getValue(this.id);
} else {
getValue(this.id);
}
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
<div id="calcOutput">
<span id="display">Enter Some Number...</span>
<hr>
</div>
<div class="text-center" id="calculator">
<button type="button" class="btn btn-danger btn-lg btn3d" id="deleteAll">AC</button>
<button type="button" class="btn btn-warning btn-lg btn3d" id="backSpace">CE</button>
<button type="button" class="btn btn-success btn-lg btn3d" id="/">/</button>
<button type="button" class="btn btn-success btn-lg btn3d" id="*">*</button><br>
<button type="button" class="btn btn-primary btn-lg btn3d" id="7">7</button>
<button type="button" class="btn btn-primary btn-lg btn3d" id="8">8</button>
<button type="button" class="btn btn-primary btn-lg btn3d" id="9">9</button>
<button type="button" class="btn btn-success btn-lg btn3d" id="-">-</button><br>
<button type="button" class="btn btn-primary btn-lg btn3d" id="4">4</button>
<button type="button" class="btn btn-primary btn-lg btn3d" id="5">5</button>
<button type="button" class="btn btn-primary btn-lg btn3d" id="6">6</button>
<button type="button" class="btn btn-success btn-lg btn3d" id="+">+</button><br>
<button type="button" class="btn btn-primary btn-lg btn3d" id="1">1</button>
<button type="button" class="btn btn-primary btn-lg btn3d" id="2">2</button>
<button type="button" class="btn btn-primary btn-lg btn3d" id="3">3</button>
<button type="button" class="btn btn-success btn-lg btn3d" id=".">.</button><br>
<button type="button" class="btn btn-info btn-lg btn3d bigButton" id="0">0</button>
<button type="button" class="btn btn-info btn-lg btn3d bigButton" id="total">=</button><br>
</div>
</div>
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';
I'm making a javascript game in which it's shown a clock and the user must select the correct alternative for the given time shown in the clock.
I want the user to be able to select an alternative and if correct its backround to turn green and if false turn orange.
<button type="button" onclick="correctClock()" id="alternative1" class="btn btn-default btn-lg btn-block">Viertel nach drei</button>
<button type="button" onclick="correctClock()" id="alternative2" class="btn btn-default btn-lg btn-block">fünf vor zwölf</button>
<button type="button" onclick="correctClock()" id="alternative3" class="btn btn-default btn-lg btn-block">zehn Minuten vor eins</button>
<button type="button" onclick="correctClock()" id="alternative4" class="btn btn-default btn-lg btn-block">Viertel vor zwölf</button>
My javascript code.
function correctClock() {
document.getElementById('alternative1').removeClass("btn-default").addClass("btn-danger");
document.getElementById('alternative2').removeClass("btn-default").addClass("btn-success");
document.getElementById('alternative3').removeClass("btn-default").addClass("btn-danger");
document.getElementById('alternative4').removeClass("btn-default").addClass("btn-danger");
}
Would this solve your problem?
HTML
<button type="button" onclick="correctClock(this)" id="alternative1" class="btn btn-default btn-lg btn-block">Viertel nach drei</button>
<button type="button" onclick="correctClock(this)" id="alternative2" class="btn btn-default btn-lg btn-block">fünf vor zwölf</button>
<button type="button" onclick="correctClock(this)" id="alternative3" class="btn btn-default btn-lg btn-block">zehn Minuten vor eins</button>
<button type="button" onclick="correctClock(this)" id="alternative4" class="btn btn-default btn-lg btn-block">Viertel vor zwölf</button>
Javascript
function correctClock(clickedButton) {
var correct_answer = "alternative1";
if (clickedButton.id == correct_answer) {
document.getElementById('alternative1').removeClass("btn-default").addClass("btn-success");
} else {
document.getElementById('alternative2').removeClass("btn-default").addClass("btn-danger");
}
}
You can do the following:
<button type="button" onclick="correctClock("alternative1")" id="alternative1" class="btn btn-default btn-lg btn-block">Viertel nach drei</button>
<button type="button" onclick="correctClock("alternative2")" id="alternative2" class="btn btn-default btn-lg btn-block">fünf vor zwölf</button>
<button type="button" onclick="correctClock("alternative3")" id="alternative3" class="btn btn-default btn-lg btn-block">zehn Minuten vor eins</button>
<button type="button" onclick="correctClock("alternative4")" id="alternative4" class="btn btn-default btn-lg btn-block">Viertel vor zwölf</button>
And check it in your callback:
function correctClock() {
if ("alternative1") {
document.getElementById('alternative1').removeClass("btn-default").addClass("btn-danger");
}
else if ("alternative2") {
document.getElementById('alternative2').removeClass("btn-default").addClass("btn-success");
}
else if ("alternative3") {
document.getElementById('alternative3').removeClass("btn-default").addClass("btn-danger");
}
else {
document.getElementById('alternative4').removeClass("btn-default").addClass("btn-danger");
}
}
First of all, you should pass the clicked element by passing 'this' as a parameter to the function correctClock
<button type="button" onclick="correctClock(this)" id="alternative1" class="btn btn-default btn-lg btn-block">Viertel nach drei</button>
<button type="button" onclick="correctClock(this)" id="alternative2" class="btn btn-default btn-lg btn-block">fünf vor zwölf</button>
<button type="button" onclick="correctClock(this)" id="alternative3" class="btn btn-default btn-lg btn-block">zehn Minuten vor eins</button>
<button type="button" onclick="correctClock(this)" id="alternative4" class="btn btn-default btn-lg btn-block">Viertel vor zwölf</button>
and then you need to add a condition, depending on the id of the element we got. Considering alternative2 is the correct answer...
function correctClock(element) {
element.id==='alternative2'?element.removeClass("btn-default").addClass("btn-success"):element.removeClass("btn-default").addClass("btn-danger")
}
That's it !
I have a list of bootstrap buttons and also a search box and I want to implement a filter function(preferably in javascript) to filter the number of buttons:
The bootstrap code is here:
https://jsfiddle.net/7zyrdnab/
<div class="row">
<div class="col-lg-2">
<div class="panel">
<input type="text" id="search" placeholder="Type to search">
<br>
<button type="button" class="btn btn-secondary">AA1009</button>
<button type="button" class="btn btn-secondary">AA1010</button>
<button type="button" class="btn btn-secondary">BA1098</button>
<button type="button" class="btn btn-secondary">BB1890</button>
<button type="button" class="btn btn-secondary">C89761</button>
<button type="button" class="btn btn-secondary">CD1667</button>
<button type="button" class="btn btn-secondary">GG7830</button>
<button type="button" class="btn btn-secondary">GF65372</button>
<button type="button" class="btn btn-secondary">BH6537</button>
<button type="button" class="btn btn-secondary">HGB562</button>
<button type="button" class="btn btn-secondary">LK9063</button>
<button type="button" class="btn btn-secondary">CP9871</button>
<button type="button" class="btn btn-secondary">IRON87</button>
<button type="button" class="btn btn-secondary">ACT567</button>
<button type="button" class="btn btn-secondary">MPO760</button>
<button type="button" class="btn btn-secondary">GH5436</button>
<button type="button" class="btn btn-secondary">NBH894</button>
<button type="button" class="btn btn-secondary">GHFDF6</button>
<button type="button" class="btn btn-secondary">US4536</button>
<button type="button" class="btn btn-secondary">MO9854</button>
</div>
</div>
</div>
The filter should work like this:
if AA is typed, only the buttons with the text "aa" should be visible.
The only suggestion i got while searching online was use list.js but I was wondering if there can be a simpler javascript search implementation.
https://jsfiddle.net/Shuaso/qhku76bu/
The jquery:
var $button = $('.btn');
$('#search').keyup(function() {
var re = new RegExp($(this).val(), "i"); // case-insensitive
$button.show().filter(function() {
return !re.test($(this).text());
}).hide();
});
Basically you want to run the function each time the user types in the input to filter the elements. You are hiding all buttons that do not match the user input.