Adding Values to Each Other - javascript

How would one go about stacking values to each other? So if you were to click on a button, it would add the numbers to each other and keep stacking on. I'm trying to add the values to a P tag's innerHTML that calculates the total but I just figured out how to display its true value without the addition of additional values.
const input = document.querySelector('input')
const button = document.querySelector('button')
const p = document.querySelector('p')
function addCal() {
const inputVal = input.value
p.innerHTML = inputVal
}
button.addEventListener('click', addCal)
<input type="text"/>
<button>Add Calories</button>
<p>0</p>

You just need to keep track of the last value somewhere and add that to the newest number.
Keep in mind that all values gotten from HTML are strings, so they must be converted (implicitly or explicitly) to numbers before math can be done. Also, .innerHTML is for when you are getting/ setting strings that contain HTML. When you aren't doing that, use .textContent.
Also note that you should always verify user input is what you think it is before you operate on it. What if the user doesn't enter anything, but clicks the button anyway? What if they enter non-numeric data?
const input = document.querySelector('input');
const button = document.querySelector('button');
const p = document.querySelector('p');
var total = null; // The running total will be kept here
function addCal() {
const inputVal = input.value;
// .parseInt() and .parseFloat() are two ways of
// explicitly converting strings that contain number
// characters to numbers. With .parseInt() the secon
// argument is the radix, which specifies what numeral
// system to use (base 10 here).
total = total + parseInt(inputVal, 10);
p.textContent = total;
}
button.addEventListener('click', addCal)
<input type="text"/>
<button>Add Calories</button>
<p>0</p>

One of the easiest ways is to use reduce to sum all the input values.
1) Pick up all the inputs with querySelectorAll.
2) Then iterate over the input elements with reduce adding each input's value to the total sum. We use +input.value to coerce the string type of the value to a number.
const inputs = document.querySelectorAll('input');
const button = document.querySelector('button');
const para = document.querySelector('p');
function addCal() {
para.textContent = [...inputs].reduce((sum, input) => {
return sum += +input.value;
}, 0);
}
button.addEventListener('click', addCal, false);
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<button>Add Calories</button>
<p>0</p>

Just do convert p tag value to int and then added up. like
function addCal() {
const inputVal = input.value
p.innerHTML = ( parseInt(p.innerHTML) + parseInt(inputVal) )
}

Related

Calculating two variables that hold input data and outputting it

I think this is a simple fix but I cannot for the life of me seem to think about why this isn't working.
I'm a complete novice at JavaScript and HTML as you can probably tell by the code below but I just want it to be functional so I can learn by it.
The goal is to take two of the input values (what the user puts into those boxes specifically) and then divide and multiply that value with a specific integer that doesn't change and output the result into a paragraph.
function calculateValues(){
let pretext = document.getElementById("preresults");
let userinput = document.getElementById("results");
let userdistanceboxinput = document.getElementById("distancebox").innerText;
let userfuelboxinput = document.getElementById("fuelinputbox").innerText;
let oneimperialgallontolitre = 4.546;
let oneimperialgallontous = 1.201;
userinput.style.visibility = 'visible';
pretext.style.visibility = 'visible';
userinput = (userdistanceboxinput / userfuelboxinput) * 4.544;
The function is tied to an onclick event on a submit button as follows:
<button type="submit" id="submitbutton" onclick="calculateValues()" value="Submit">Submit</button>
Any help with this would be appreciated.
To get a value in Javascript, you can do this:
<input type="number" id="input1">
const input1 = document.getElementById('input1'); // retrieve the HtmlInputElement
const value1 = input1.target.value; // retrieve the value of this element
If you want to set a HtmlInputElement value you can do (same html):
const input1 = document.getElementById('input1'); // retrieve the HtmlInputElement
input.target.value = value1 * 21545 // set value of HtmlInputElement

How to have always a different variable chosen in javascript?

What do I need to add to the following code, so that a different variable is chosen each time and not the same letter occurs after itself.
goal is a situation like this:
after pressing run: change = a
after pressing run second time: change = b
after pressing run third time: change = a
after pressing run for the fourth time: change = c
after pressing run for the fifth time: change = b
...
var ch = ['a', 'b', 'c']
change = document.getElementById("1").innerHTML = ch[Math.floor(Math.random() * ch.length)];
<label id="1"> </label>
You'll need to add a system where you remove the character from the list after it has been selected. This way, when you call the random select function again you won't be able to select the same value twice in a row.
However you do need to save the item you've selected somewhere in a variable so that you're able to add it back to the list once a new character has been chosen.
The snippet below demonstrates this principle. Try it out and follow the annotations to figure out the logic. It even works when you add more options. No chances of the same consecutive results.
const output = document.getElementById('output');
const button = document.getElementById('select');
// Available options.
const options = ['a', 'b', 'c'];
// Previously selected option.
let selectedOption = null;
// Function which selects a random item from
// the options array.
const selectRandomOption = () => {
// Get a random index and select the option.
const index = Math.floor(Math.random() * options.length);
const option = options[index];
// If there is a previous selected option..
if (selectedOption !== null) {
// ..then add it back to the list.
options.push(selectedOption);
}
// Store the newly selected option..
selectedOption = option;
// ..and remove it from the list so it cannot
// be selected again until the next time
// selectRandomOption is called.
options.splice(index, 1);
// Return the selected option.
return option;
};
// Trigger the selectRandomOption when clicking
// on the button and show the result in the output.
button.addEventListener('click', () => {
const option = selectRandomOption();
output.value = option;
});
<output id="output"> </output>
<button id="select">Select random but not the same</button>
If I understand you correctly, what you want is called a "toggle" functionality.
You can achieve that with the following code:
var span = document.getElementById("value");
span.innerHTML = 'on';
function toggle(){
span.innerHTML = (span.innerHTML == 'on' ? 'off' : 'on');
}
<p>
value: <span id="value"></span>
</p>
<button onClick="toggle()"> click me </button>
You should remove the value from index once its been used
rand = Math.floor(Math.random()*ch.length);
change = document.getElementById("1").innerHTML = ch[rand];
ch.splice(rand,1)
I'm reading this as a toggle between a and b. Code below does that.
let displayDiv = document.getElementById("result");
let [a,b] = ['a','b'];
//one-liner swap & display
toggle = () => {
displayDiv.innerText = ([a,b] = [b,a])[0];
}
<button onclick="toggle()">Run</button>
<div id="result">a</div>
To cycle through a list of options, you can use Array.shift() and re-insert the previous content of the output-element back into the array.
let options = ["B", "C", "D", "E"];
document.querySelector("button").addEventListener("click", () => {
let output = document.querySelector("#output");
options.push(output.innerHTML);
output.innerHTML = options.shift();
});
<span id="output">A</span>
<button>New value</button>
To select a random value of a list, randomize the selection using Math.random(), and save the content of the HTML-element back inside the array. Then, remove that array-element and set the HTML-element's content to that value.
let options = ["B", "C", "D", "E"];
let output = document.querySelector("#output");
document.querySelector("button").addEventListener("click", () => {
options.push(output.innerHTML);
let newValue = options[Math.floor(Math.random() * options.length)];
output.innerHTML = newValue;
options.splice(options.indexOf(newValue), 1);
});
<span id="output">A</span>
<button>New value</button>

How to get the value of an input type number and put it into a global variable JS

I want to get the value of an input type number and put it into a global variable. But in the console I get undefined. I need to use the value in other functions. How can I do that?
const bet = document.querySelector('#bet');
let Inputvalue;
bet.addEventListener('change', checkBet)
function checkBet(e) {
Inputvalue = e.target.value;
}
console.log(Inputvalue)
<input type="number" id="bet" value="" name="bet">
The checkBet() function will only be called after you change the value in the input. However, console.log() gets called right away, just as the JS parser reads the file. Since you've not assigned any value to the variable, you will get undefined.
You should either initialize the variable with a value (like 0), or move the console.log() inside the checkBet() function.
Option 1:
const bet = document.querySelector('#bet');
let Inputvalue;
bet.addEventListener('change', checkBet)
function checkBet(e) {
Inputvalue = e.target.value;
console.log(Inputvalue)
}
Option 2:
const bet = document.querySelector('#bet');
let Inputvalue = 0;
bet.addEventListener('change', checkBet)
function checkBet(e) {
Inputvalue = e.target.value;
}
console.log(Inputvalue)
Try this.
const bet = document.querySelector('#bet');
let Inputvalue;
bet.addEventListener('change', checkBet);
function checkBet(e) {
Inputvalue = e.target.value;
console.log(Inputvalue)
}
<input type="number" id="bet" name="bet"/>
Hope this helps

Using querySelector to get each letter a user inputs

Trying to make a web page that will get each letter a user inputs and output it in a phonetic alphabet. For example (user types: Hello)(Output: Hotel , Echo , Lima, Lima, Oscar). This is what I have so far just need some guidance on how to get the value of each letter and compare it to like an Array to get the output.
//define UI variables
const userInput = document.querySelector('#input');
const phoneticAlphabet = ["Alpha"," Bravo","Charlie"];
//load all event listeners
loadEventListeners();
function loadEventListeners() {
//add submit event
form.addEventListener('submit', submitInput);
}
//submit user input
function submitInput(e) {
console.log(userInput.value);
if (userInput.value === '') {
alert('Add Input');
}
e.preventDefault();
}
I presume that you would like to replace non-convertible characters from the input. For the same, I am using regular expression. I have also added the response in a "p" tag. And the code runs on clicking "Submit".
Update:
Extended my array for all alphabets :)
Update 2:
Thanks #CharlieBatista for pointing out. Now, the input accepts uppercase characters as well.
//define UI variables
const form = document.phoneticForm;
const userInput = document.querySelector('#input');
const output = document.querySelector('#output');
const phoneticAlphabet = ['Alpha','Bravo','Charlie','Delta','Echo','Foxtrot','Golf','Hotel','India','Juliet','Kilo','Lima','Mike','November','Oscar','Papa','Quebec','Romeo','Sierra','Tango','Uniform','Victor','Whiskey','X-ray','Yankee','Zulu'];
//load all event listeners
loadEventListeners();
function loadEventListeners() {
//add submit event
form.addEventListener('submit', submitInput);
}
//submit user input
function submitInput(e) {
e.preventDefault();
var value = userInput.value;
if (value === '') {
alert('Add Input');
} else {
value = value.replace(/[^a-zA-Z]/gi,'');
userInput.value = value;
value = value.toLowerCase();
var outputArr = [];
for(var i = 0; i < value.length; i++){
outputArr.push(phoneticAlphabet[value.charCodeAt(i)-97]);
}
output.innerHTML = outputArr.join(', ');
}
}
<form name="phoneticForm">
<input type="text" id="input">
<input type="submit">
</form>
<p id="output"></p>
You can use the key property on the keydown event of the field to get the character that was pressed.
Then check if the key is a printable key using key.length === 1 (see this answer).
If the key is printable, convert it to uppercase, then to its character code using String.prototype.charCodeAt() and then subtract 65 from it (character A). This will give you the index in your array.
If this index is within the bounds of the array, access the array and print the character.
const phoneticAlphabet = ['Alpha','Bravo','Charlie','Delta','Echo','Foxtrot','Golf','Hotel','India','Juliet','Kilo','Lima','Mike','November','Oscar','Papa','Quebec','Romeo','Sierra','Tango','Uniform','Victor','Whiskey','X-ray','Yankee','Zulu'];
document.querySelector('#input').addEventListener('keydown', e => {
const isPrintable = e.key.length === 1;
console.clear();
if (isPrintable) {
const idx = e.key.toUpperCase().charCodeAt(0) - 65;
if (idx >= 0 && idx < phoneticAlphabet.length) {
const phoneme = phoneticAlphabet[idx];
console.log(phoneme);
}
}
});
<input type="text" id="input">

How can I get a array as an input value inserted into an HTML input field?

I've been on this all day.
HTML Code
<label>Input values</label>
<input type="text" id="arrays" placeholder="Enter Array" >
<button id="objectify" type= "button">Click</button>
<div id="results"></div>
JavaScript
var input= document.getElementById('arrays').value; //["book", 3, "pin", 4];//
var btn = document.getElementById('objectify');
var output = document.getElementById('results');
function objectifyArr(x) {
var myObject = {
String: [],
Number: []
};
for (var i = 0; i < x.length; i++) {
if (typeof x[i] === 'string' || x[i] instanceof String){
myObject.String.push(x[i]);
} else if (typeof x[i] === 'number' || x[i] instanceof Number){
myObject.Number.push(x[i]);
}
}
return myObject;
}
btn.onclick = function () {
output.textContent = JSON.stringify(objectifyArr(inputValue));
}
The code seems to work when I assign 'inputValue' a range of array values but doesn't when I get the array via getElementbyId.value. Is there an input type for arrays specifically or did I assign the wrong value to my variable?
Regardless of what the mistake is, I'll be glad if someone pointed it out for me.
How about just using JSON.parse() and waiting to get the value of the input until you actually click the button?
Also (FYI), label requires that you either nest the element that it is a label for within it or that you add the for attribute and give it the value of the id of the element that it is a label "for".
var input= document.getElementById('arrays'); //["book", 3, "pin", 4];//
var btn = document.getElementById('objectify');
var output = document.getElementById('results');
btn.addEventListener("click", function () {
let myArray = JSON.parse(input.value);
output.textContent = myArray;
console.log(myArray);
});
<label for="arrays">Input values</label>
<input id="arrays" placeholder="Enter Array" value='["book", 3, "pin", 4]'>
<button id="objectify" type= "button">Click</button>
<div id="results"></div>
Your first problem is that you declare this in the top of your JS file:
var input= document.getElementById('arrays').value
This is literally saying "assign the current value of the element to my input variable". Obviously, the input element at the start of the script is empty, therefore the value is ''.
After that, the other problem is that as your input only accepts text, all the characters inside will be String type, so looping and checking for the typeof of each character will always yield it as a String.
A workaround for that would be using a RegExp.
Here's a working JSFiddle

Categories

Resources