JS NaN after array[index] - javascript

I just started programming with js again and having some trouble.
This is the code i have problems with:
var actual = [10,50,20];
var sum = 0;
for(var i = actual.length; i > 0; i--){
sum = sum + actual[i];
}
What did i do wrong?

Start loop from actual.length-1, because every array starts from 0, so last element is actual.length-1 not actual.length.

I see Your calculator code is too complicated.
You do low level operation to add just "1" You multiply all things to 10 and add 1.
Be simple (;
var inputElement = document.getElementById("input");
var resultElement = document.getElementById("result");
var accept = [0,1,2,3,4,5,6,7,8,9,'-','+','calc'];
var input = [];
function op(value){
if(accept.indexOf(value) < 0) {
return;
}
if(value == 'calc') {
return calc();
}
input.push(value);
inputElement.innerHTML = input.join('');
}
function calc() {
resultElement.innerHTML = eval(input.join(''));
input = [];
}
<button onclick="op(1)">1</button>
<button onclick="op(2)">2</button>
<button onclick="op(3)">3</button>
<br/>
<button onclick="op(4)">4</button>
<button onclick="op(5)">5</button>
<button onclick="op(6)">6</button>
<br/>
<button onclick="op(7)">7</button>
<button onclick="op(8)">8</button>
<button onclick="op(9)">9</button>
<br/>
<button onclick="op(0)">0</button>
<button onclick="op('.')">.</button>
<button onclick="op('calc')">=</button>
<hr/>
<button onclick="op('+')">+</button>
<button onclick="op('-')">-</button>
<hr/>
INPUT:<div id="input"></div>
DISPLAY:<div id="result"></div>

Related

How to do a mini calculator using a single event Listener instead of onclick events in each button?

The challenge is to do a simple mini calculator with one input, 4 buttons, and an output.
The input is to add a number that will appear in the output immediately, next I will choose one of the four buttons (+,-,*,/)to do the math and next write again another number on the input. In the output will appear the result of that operation, further will continuing to do maths by clicking again in the buttons and add another number, and actualizing always the result.
I have done this before with onclick event in each button and using a prompt to write the numbers. now I want to use an input to write the numbers and using one event listener to all the buttons. Can anybody help me with the solution and explain to me each step?
This is my code so far :
let input =document.querySelector('#input');
let output =document.querySelector('#output');
let divButtons = document.querySelector('#buttons');
let messageOutput = (message) =>{
output.innerHTML = message;
}
messageOutput(input.value); // this doesn't work. What I miss to do show the input in the output?
divButtons.addEventListener('click', () =>{
//do something
})
<section class="container">
<h1 class="heading">Do some maths</h1>
<div class="calculator">
<input class="inputNumbers" id="input" type="number" placeholder="choose a number here">
<div class="buttons" id="buttons">
<button id="plus" class="btn btn-plus">+</button>
<button id="minus" class="btn btn-minus">-</button>
<button id="multiply" class="btn btn-multiply">*</button>
<button id="divide" class="btn btn-divide">/</button>
</div>
<div id="output" class="visor"></div>
</div>
</section>
I am new so I need help to solve this challenge and understand what should I have to do.
Thank you
Modified JS code a bit, using the listener you already wrote, let me know if you need more explaining. Hope it helps.
let input =document.querySelector('#input');
let output =document.querySelector('#output');
let divButtons = document.querySelector('#buttons');
let a = null;
let b = null;
let op = null;
let messageOutput = (message) =>{
output.innerHTML = message;
}
messageOutput(input.value); // this doesn't work. What I miss to do show the input in the output?
divButtons.addEventListener('click', (event) =>{
//checking if button is pressed
if(event.target.type = 'submit') {
//if a is not set before, meaning first time input
if(a == null) {
a = Number(input.value);
} else {
// second number
b = Number(input.value);
if(op == 'plus') {
a += b;
} else if(op == 'minus') {
a -= b;
}else if(op == 'multiply') {
a *= b;
} else {
a /= b;
}
}
//saving the operator that was pressed
op = event.target.id;
//showing output
output.innerHTML = a + " " + op;
//resetting input on each button pressed.
input.value = '';
}
});
<section class="container">
<h1 class="heading">Do some maths</h1>
<div class="calculator">
<input class="inputNumbers" id="input" type="number" placeholder="choose a number here">
<div class="buttons" id="buttons">
<button id="plus" class="btn btn-plus">+</button>
<button id="minus" class="btn btn-minus">-</button>
<button id="multiply" class="btn btn-multiply">*</button>
<button id="divide" class="btn btn-divide">/</button>
</div>
<div id="output" class="visor"></div>
</div>
</section>
Hope this helps. Modified your snippet a little and added a few variables.
let input = document.querySelector("#input");
let output = document.querySelector("#output");
let divButtons = document.querySelector("#buttons");
let result = null;
let selectedOperation = null;
let messageOutput = message => {
output.innerHTML = message;
};
divButtons.addEventListener("click", event => {
//do something
let id = event.target.id;
let value = parseInt(input.value);
switch (selectedOperation) {
case "plus":
result += value;
break;
case "minus":
result -= value;
break;
case "multiply":
result *= value;
break;
case "divide":
result /= value;
break;
default:
result = value;
break;
}
selectedOperation = id;
input.value = "";
messageOutput(`${result} ${selectedOperation}`);
});
Save your input number into a variable, then save the math function clicked by the user into a variable, then apply it to the saved input number using the current value the user has input as the factor.
Something like this:
let input = document.querySelector('#input');
let output = document.querySelector('#output');
let inputnumber = 0;
let subtotal = 0;
let total = 0;
let calculate = 0;
let x;
let y;
input.oninput = (e) => {
if(subtotal == 0) {
output.value = e.target.value;
}
x = Number(e.target.value);
y = Number(subtotal);
switch (calculate) {
case "btn-divide":
calc = y / x;
break;
case "btn-multiply":
calc = y * x;
break;
case "btn-plus":
calc = x + y;
break;
case "btn-minus":
calc = y - x;
break;
case 0:
calc = x;
break;
}
output.value = calc;
}
const divs = document.querySelectorAll('#buttons');
divs.forEach(el => el.addEventListener('click', event => {
calculate = event.target.classList[1];
input.value = null;
subtotal = calc;
}));
<section class="container">
<h1 class="heading">Do some maths</h1>
<div class="calculator">
<input class="inputNumbers" id="input" type="number" placeholder="choose a number here">
<div class="buttons" id="buttons">
<button id="plus" class="btn btn-plus">+</button>
<button id="minus" class="btn btn-minus">-</button>
<button id="multiply" class="btn btn-multiply">*</button>
<button id="divide" class="btn btn-divide">/</button>
</div>
<input id="output" type="number" class="visor" value=0>
</div>
</section>
Term you are looking for is called event delegation.
let input =document.querySelector('#input');
let output =document.querySelector('#output');
let divButtons = document.querySelector('#buttons');
let messageOutput = (message) =>{
output.innerHTML = message;
}
messageOutput(input.value); // this doesn't work. What I miss to do show the input in the output?
divButtons.addEventListener('click', (e) =>{
console.log(e.target.id)
})
<section class="container">
<h1 class="heading">Do some maths</h1>
<div class="calculator">
<input class="inputNumbers" id="input" type="number" placeholder="choose a number here">
<div class="buttons" id="buttons">
<button id="plus" class="btn btn-plus">+</button>
<button id="minus" class="btn btn-minus">-</button>
<button id="multiply" class="btn btn-multiply">*</button>
<button id="divide" class="btn btn-divide">/</button>
</div>
<div id="output" class="visor"></div>
</div>
</section>
Basically you do not attach event listeners on every element, but you attach same event on parent of all elements and you can track the source of event using e.target.

how to store elements in array but by trucating leading zeros

function getResult(exp)
{
var result, num = [], signs = [];
//console.log("here" + exp.lastIndexOf(""));
parts = exp.split(/([+-/*])/);
for (var i = 0; i < parts.length; i++)
{
var item = parts[i].trim()
if (isNaN(item))
signs.push(item);
else
num.push(item);
}
console.log(num);
}
function maincalculation()
{
var txtprint = document.getElementById("texa");
if(!document.getElementById("texa").value)
{
}
else
{
var result = getResult(txtprint.value);
txtprint.value = result;
}
}
<html>
<body>
<div class = "textbox">
<!-- <input type="text" value="" id="tex" />
<input type="button" value="equal" onclick="equal()" id="add" />
<input type="button" value="click-count" onclick="click()" id="click" />
<p><input type="button" name="button" value="Saying Hello" id="hello" onclick="hello();"/></p> -->
<br><br>
<input types="text" id="texa">
<input type = "button" value = "calculate" onclick="maincalculation()" />
</div>
</body>
</html>
My code contain text-box it takes the whole String type by the user now i want to store the array elements separately in array. it stores perfectly as it is but i want to store array elements like by truncating leading zeros i have use regex function num = num.replace(/^[0]+/g,""); it eliminate all the leading zeros as i want but when user type only 0 it will eliminate 0 value too and stores the blank so is there any way that if user type suppose like [10+30+001+08*0/89] then this value must be store like this [10+30+1+8*0/89] truncating all leading zeros but not the single zero value.
Example for my comment:
var regex = new RegExp('0*(?=[0-9])+', 'g');
console.log('0'.replace(regex, '')); //0
console.log('0000'.replace(regex, '')); //0
console.log('01'.replace(regex, '')); //1
console.log('00106'.replace(regex, '')); //106
console.log('4'.replace(regex, '')); //4
console.log('10+30+001+08*0/89'.replace(regex, ''));
function getResult(exp) {
var result, num = [], signs = [];
parts = exp.split(/([+-/*])/);
for (var i = 0; i < parts.length; i++) {
var item = parts[i].trim()
if (isNaN(item))
signs.push(item);
else
num.push(+item.replace(regex,''));
}
console.log(num);
}
function clickMe() {
getResult($('#calculation').val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="calculation" value="10+30+001+08*0/89"/>
<button onclick="clickMe()">Get result</button>

Read one item of array onclick javascript

<div id="wrapper">
<div class="quotes">
<p id="par"></p>
</div>
<button class="btn" onClick="randomQuote()">button</button>
</div>
function randomQuote () {
var array = [1,20,50,100];
}
document.getElementById("btn").onclick = randomQuote;
document.getElementById("par").innerHTML = array[0];//then on another btn click array[1]...
for(var i=0; i<array.length;i++){
quote[i];
}
On "btn" click number 1 from array is shown in "par" paragraph
on another btn click number 2 shows up and 1 dissapear, and so on...
Use counter cpt as index to loop through the array and show the values :
var array = [1,20,50,100];
var cpt = 0;
//Init the 'par' div before click
document.querySelector("#par").innerHTML = array[cpt];
function randomQuote ()
{
if(cpt<array.length-1)
cpt++;
else
cpt=0;
document.querySelector("#par").innerHTML = array[cpt];
}
<div id="wrapper">
<div class="quotes">
<p id="par"></p>
</div>
<button class="btn" onClick="randomQuote()">button</button>
</div>
Minified version could be :
function randomQuote ()
{
document.querySelector("#par").innerHTML = array[cpt<array.length-1?++cpt:cpt=0];
}
Snippet using Random color as you comment say :
var array = ["Quotes 1","Quotes 2","Quotes 3","Quotes 4"];
var cpt = 0;
//Init the 'par' div before click
document.querySelector("#par").innerHTML = array[cpt];
//Init Random Color before click
getRandomColor();
function randomQuote()
{
if(cpt<array.length-1)
cpt++;
else
cpt=0;
document.querySelector("#par").innerHTML = array[cpt];
}
function getRandomColor()
{
document.querySelector("#par").style.backgroundColor = '#'+Math.floor(Math.random()*16777215).toString(16);
}
<div id="wrapper">
<p id="par"></p>
<button id="btn" onClick="randomQuote();getRandomColor()">Next quote</button>
</div>
Is this what you want?
var counter = 0;
function randomQuote () {
var array = [1,20,50,100];
document.getElementById("par").innerHTML(array[counter++]);
}
save the index, increment it on each click and then reset it when its undefined.
var index = -1;
function randomQuote() {
var array = [1, 20, 50, 100];
document.getElementById('par').innerText = (array[++index] || array[index=0]);
}
<div id="wrapper">
<div class="quotes">
<p id="par"></p>
</div>
<button class="btn" onClick="randomQuote()">button</button>
</div>

How to reset a counter back to 0 with a button in javascript?

I have a counter in javascript right now and a button that adds 1 value to the counter, this is what I have so far:
var counter = 0;
var a = 0;
var add = function(valueToAdd){
a += valueToAdd;
document.getElementById('Value').innerHTML = a;
}
Value $<span id="Value">0</span>
<button width="500" height="500" id = add class="button button1" onclick="javascript:add(1)">Add Value</button>
I need a button to reset the counter back to 0 any help is appreciated.
Add a button, reset function and set values to "0" as shown in code below:
<button width="500" height="500" id ="reset" class="button button1"
onclick="javascript:reset()">Reset Value</button>
<script type="text/javascript">
var reset= function(){
a = 0;
document.getElementById('Value').innerHTML = a;
}
</script>
BTW you declared var count = 0 in your code (question) but not using that (apparently).
Some tips:
You correctly stored a variable to keep track of the counter, all you needed to do in a reset function was to change the value back to 0.
Keep your Javascript away from your HTML. Here's a good article
Your code should be properly formatted when posting on Stack Overflow.
Here's a cleaner solution:
HTML:
Value $<span id="Value">0</span>
<button id="add">Add Value</button>
<button id="reset">Reset</button>
Javascript:
var a = 0;
var add = function(valueToAdd) {
a += valueToAdd;
document.getElementById('Value').innerHTML = a;
}
var reset = function() {
a = 0;
document.getElementById('Value').innerHTML = 0;
}
var addButton = document.querySelector("#add");
var resetButton = document.querySelector("#reset");
addButton.addEventListener("click", function() {
add(1);
})
resetButton.addEventListener("click", function() {
reset();
})
JSFiddle: https://jsfiddle.net/sfh51odm/
Do not define a out of function as a general variable. Every time set the current value to a and continue. So you can get back to zero:
var counter = 0;
var add = function(valueToAdd){
var a = parseInt(document.getElementById('Value').innerHTML);
a += valueToAdd;
document.getElementById('Value').innerHTML = a;
}
function reset(){
document.getElementById('Value').innerHTML=0;
}
Value $<span id="Value">0</span>
<button width="500" height="500" id = add class="button button1" onclick="javascript:add(1)">Add Value</button>
<button width="500" height="500" id = add class="button button1" onclick="javascript:reset()">Reset</button>
var a = 0;
var displayValue = document.getElementById('Value');
var updateValue = function () {
displayValue.innerHTML = a;
};
var add = function (valueToAdd) {
a += valueToAdd;
updateValue();
};
var reset = function () {
a = 0;
updateValue();
};
Value $<span id="Value">0</span>
<button onclick="add(1)">Add 1</button>
<button onclick="reset()">Reset</button>
if you need to do a page refresh (like if you press F5 on the keyboard) this will work for you.
the "location.reload();" will work also.
change '.again' to a btn name you want.
document.querySelector('.again').addEventListener('click', function () { location.reload(); });

Keep button from decrementing a number after 1st use with Javascript

I'm trying to keep track of the number of items a user has clicked on by removing one from the counter span using a basic JS function. I have to keep track of anywhere between 5 to 10 items so each time the button is clicked I am removing one from the div span that keeps count. It's working but I do not want it going to negative values. How do I keep the button from removing 1 after it has been used once? Basically, I want the function to only fire once for each button.
Here is the codepen as it is now:
CODEPEN
Here is what I have right now:
var currentValue = 9;
var add = function(valueToAdd){
currentValue += valueToAdd;
document.getElementById('number').innerHTML = currentValue;
if (this.currentValue == 0) {
alert("YOU ARE AT 0 ");
currentValue - 0
}
if (!isNaN(currentValue) && currentValue > 0) {
// Decrement one
currentValue - 1;
} else {
return false;
}
};
HTML:
<div id="text">Number of items:<span id="number">9</span><div>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
You have great interest in inserting the buttons programmatically, you'll have a much greater flexibility. And you can hook the function to a function that you bind to have the right this .
Below is the code for buttons that handle a 'quantity' property, and disable themselves when quantity reaches 0.
http://codepen.io/anon/pen/gJtry
<div id="text">Number of items:<span id="number">9</span>
<div id="oneTimeButtons">
</div>
<div id='youDidIt' hidden>!!! You did it !!!</div>
code :
var buttonCount = 9;
var quantityPerButton = 1; // try 2 or more
var totalValue = 0;
var gID=document.getElementById.bind(document);
var elem = gID('oneTimeButtons');
for (var i=0; i<buttonCount; i++) {
var bt = document.createElement('button');
bt.id='qttBt'+i;
bt.onclick = add.bind(bt, -1);
bt.quantity=quantityPerButton;
totalValue+=bt.quantity;
bt.buildTitle = function( i) {
this.innerHTML='Qtty button '+i+' ('+this.quantity+')';
}.bind(bt, i);
bt.buildTitle();
elem.appendChild(bt);
}
gID('number').innerHTML=totalValue;
function add (valueToAdd) {
this.quantity+=valueToAdd;
this.buildTitle();
if (this.quantity ==0) this.disabled=true;
totalValue += valueToAdd;
gID('number').innerHTML = totalValue;
if (totalValue == 0) {
console.log("YOU ARE AT 0 ");
gID('youDidIt').hidden=false;
}
};

Categories