Add value with onclick JavaScript function - javascript

I have small system that needs to track sales. I have a button with a JS function called incrementValue(), this one does a value++ and works fine. But I need to have a function called that takes the price field from JSON and adds that price by the click of the same button (incrementValueRevenue()). The button works fine the with the first click, but after that the incrementValueRevenue function stops.
So for this example when you've clicked the button three times, incrementValue() will show 3 and incrementValueRevenue() should show 105.
This is what i have:
function incrementValue() {
var value = document.getElementById('items-sold').value;
value++;
document.getElementById('items-sold').value = value;
}
function incrementValueRevenue() {
var myJSON = '{ "price":"35" }';
var myObj = JSON.parse(myJSON);
document.getElementById('total-revenue').value = myObj.price;
myObj.price += myObj.price;
}
This is my HTML
<form>
<input type="button" onclick="incrementValue(); incrementValueRevenue();" value="+" />
</form>
Thanks in advance.
PS. Yes, I am very rookie, and I have not been able to find a working solution anywhere.

Do it in only one function, then multiply the total revenue by the items sold:
function incrementValueAndRevenue() {
var value = document.getElementById("items-sold").value;
value++;
document.getElementById("items-sold").value = value;
var myJSON = { price: 35 };
var revenue = myJSON.price * value;
document.getElementById("total-revenue").value = revenue;
}

You initiate myObj on every incrementValueRevenue call so the value is always reset.
You can declare the variable outside the function scope so it is initialized once and have another value parsing the JSON!
var myObj = {};
myObj.price = 0;
function incrementValueRevenue() {
var myJSON = '{ "price":"35" }';
var myObjPrice = JSON.parse(myJSON);
document.getElementById('total-revenue').value = myObj.price;
myObj.price += myObjPrice.price;
}

function incrementValueRevenue() {
var myJSON = '{ "price":35 }';
var myObj = JSON.parse(myJSON);
let revenue = document.getElementById('total-revenue');
revenue.value = +revenue.value + myObj.price
}
First of all your price should by a number, later we take the total-revenue input and store it in variable, to add number to input value we need to convert that input value to number first ( if you dont do it the out would be "35353535...") by using "+" operator.

Related

How to keep updating value of a variable by clicking on a button in JavaScript after it was entered in INPUT first?

I'm a rookie JS programmer making first steps into programming, so I appreciate your help to help me learn it.
I have created a function that adds 5 to a value entered by the user in INPUT. The result is displayed in . It works perfectly. After clicking the button the result shows up. However, I want to use the same button to keep adding another 5 to the output value without entering a new value in the INPUT.
I've tried:
-declaring the undefined value (let sum; )outside the function to make the variable global but it didn't work.
I was thinking about:
storing the value in an empty array but I don't know how to access it with my button (I don't think it's the right way)
removing the eventListener from the button and creating another function to keep adding 5 by clicking (a not changing the input value).
let sum;
let sum2;
function adder5() {
let userNumber = Number(document.querySelector("#yourNumber").value);
sum = userNumber + 5;
document.querySelector("#output").textContent = sum;
}
document.querySelector("#btn").addEventListener("click", adder5);
function adderContinue(sum) {
document.querySelector("#btn").addEventListener("click", function () {
sum2 = sum + 5;
});
document.querySelector("#output").textContent = sum2;
}
<input id="yourNumber" type="number" />
<button id="btn">Calculate</button>
<p id="output"></p>
I appreciate your help. Any hint will do because I'm stuck. BTW I realize that variable SUM changes into SUM2 after the first click event, but the code should work at least once.
You could use the input field's event to update the cached value and update it on button click.
const input = document.getElementById('input'),
button = document.getElementById('button'),
output = document.getElementById('output');
let value = input.valueAsNumber;
input.oninput = function () {
value = this.valueAsNumber;
};
button.onclick = function () {
value += 5;
output.textContent = isNaN(value) ? '' : value;
};
<input type="number" id="input" />
<button id="button">Calculate</button>
<p id="output"></p>
You may create a variable to store old user input and check if it is equivalent to the new user input or not.
If it is equal then only add 5 to the sum
Else add the user input with 5
let sum = 0;
let oldUserInput = 0;
function adder5() {
let currentUserInput = Number(document.querySelector("#yourNumber").value);
if(currentUserInput === oldUserInput){
sum = sum + 5;
} else {
sum = currentUserInput + 5;
// Update the oldUserInput to the current
oldUserInput = currentUserInput;
}
document.querySelector("#output").textContent = sum;
}
document.querySelector("#btn").addEventListener("click", adder5);

How to fix this 'undefined' when i try to display the sum in the element "pro1'

Im trying to get the value from the element 'amt1' which increases everytime i onclick a button and display it on the element 'pro1'. however, i am receiving the value 'undefined' im really new to javascript. hope someone could help me. thank you in advance!
var add1 = function(sum) {
return function () {
document.getElementById("amt1").innerHTML = ++sum;
var price1 = document.getElementById("amt1").value;
return price1;
};
}(0);
var total1 = price1*parseFloat(119.90);
function displayPrice(){
document.getElementById('pro1').innerHTML = total1;
}
price1 is a local variable in the lexical scope of the function returned by sum function. It's value is not available in the outer scope when you try to multiply it by 119.90.
You can get the price from the element amt1 dynamically inside displayPrice function instead.
Also if amt1element is not an input then you should use .textContent property of the element instead of .value:
var add1 = function(sum) {
return function () {
document.getElementById("amt1").innerHTML = ++sum;
};
}(0);
document.querySelector('button').addEventListener('click', add1)
function displayPrice(){
var price = parseFloat(document.getElementById("amt1").textContent);
var total = price * 119.90;
document.getElementById('pro1').innerHTML = total;
}
document.querySelectorAll('button')[1].addEventListener('click', displayPrice)
<p id="amt1">0</p>
<button>Add</button>
<br><br>
<button>Total</button>
<p id="pro1"><p>

How do I calculate the sum of numbers stored in LocalStorage?

I am new to JSON, so bear with me!
I am working on a website that stores values to LocalStorage via inputs. Each form input has the following function (only difference is formInput2, formInput3)
function formInput(e) {
// Save userInput from input
// Get form values
var input = document.querySelector('.input').value;
this.style.visibility = 'hidden';
smtBtn.style.display = 'inline-block'
var userInput = {
answer: input
}
// Test if bookmark is null
if (localStorage.getItem('bookmarks') === null) {
// Init Array
var bookmarks = [];
// Add to array
bookmarks.push(userInput);
// Set to LocalStorage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
} else {
// Get Bookmarks from LocalStorage
var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
// Add bookmark to array
bookmarks.push(userInput);
// Reset back to LocalStorage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
}
// Refetch bookmarks
fetchBookmarks();
// Prevent form from submitting
e.preventDefault();
}
I need to add the three numbers that are in local storage, and I am using this function:
function bookmarkMath() {
var bm1 = JSON.parse(localStorage.getItem('bookmarks')),
total = 0,
i;
for (i = 0; i < bm1.length; i++) {
total += bm1[i].answers;
}
console.log(total);
}
}
But alas, my output is NaN. :(
Any help would be very appreciated!!!!!!!
edit: In dev tools, this is what I get back with console.log(LocalStorage) - the numbers I have entered in the form on the site.
Storage {bookmarks: "[{"answer":"2"},{"answer":"4"},{"answer":"5"}]", length: 1}
bookmarks: "[{"answer":"2"},{"answer":"4"},{"answer":"5"}]"
length: 1
__proto__: Storage
Edit 2: I have updated the second ]function to include the JSON.parse. But now I am getting just the numbers 0245 as my result, NOT the sum of 0+2+4+5. Any help?? :p
You are on the right track by doing JSON.parse(). However, the value is in a string. You can see quote at the value it is mean will be threated as a string. You should convert it to number format like following:
total += parseInt(bm1[i].answers);
If you don't want to do parseInt() then your output should be :
{"answer": 2} //this one mean your value is Number
Instead:
{"answer":"2"} //this one mean your value is in String
I think I see it ... this statement looks "wrong, yet something that JavaScript would accept!"
var bm1 = JSON.parse(localStorage.getItem('bookmarks')),
total = 0,
i;
Notice the commas.
Instead, write this as three separate lines:
var var bm1 = JSON.parse(localStorage.getItem('bookmarks'));
var total = 0;
var i;
const bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || []
const totalAnswers = bookmarks.map(o => +o.answer).reduce((a, b) => a + b)

Placing code in my Javascript array

I have the following problem,
I have made a form with alot of input fields. Where if the user types a 1 it will show the price immediately next to it. My code for this is this:
var priceMargherita = 7;
var numPizzaMargheritaInput = document.getElementById('countMargherita');
var priceMargheritaLabel = document.getElementById('totalMargherita');
function onNumPizzaMargheritaInputChange(e){
var totalMargherita = priceMargherita * parseInt(e.target.value);
var formattedPrice = '\u20ac '+totalMargherita.toFixed(2);
priceMargheritaLabel.innerHTML = '';
priceMargheritaLabel.appendChild(document.createTextNode(formattedPrice));
}
numPizzaMargheritaInput.addEventListener('change', onNumPizzaMargheritaInputChange, false);
and it places the price like this:
<td>Pizza Margherita</td>
<td><input type="number" id="countMargherita" class="formnumbers" name="PizzaMargherita" onChange="validateForm(this)" min="1" max="99"/></td>
<td><span id="totalMargherita"></span></td>
Now my problem is that i have 11 products like this Pizza Margherita. And at the moment i have 11 pieces of code like the top one. I think this can be done in an array since the only things that change are some names.
Correct me if i'm wrong since im nowhere experienced in JS nor Arrays.
Any help is greatly appreciated!
For me, the simplest way to do it is to NOT use arrays or ids.
If you can change the html, you should add the price as a data-attribute, and then you can have a generic code :
<td>Pizza Margherita</td>
<td><input type="number" class="formnumbers" name="PizzaMargherita"
onChange="changeTotalFromCount(this)" min="1"
max="99" data-unitPrice="7" /></td>
<td></td>
JS :
function changeTotalFromCount(input) {
var unitPrice = parseFloat(input.getAttribute("data-unitPrice"));
var count = input.value;
var price = unitPrice * count;
var formattedPrice = '\u20ac ' + price.toFixed(2);
var label = input.parentNode.nextElementSibling;
label.innerHTML = '';
label.appendChild(document.createTextNode(formattedPrice));
}
Rather than arrays, I think the word you're looking for is loops. Here is a way to factor your program using an object and a loop:
var prices = {
Margherita: 7,
Hawaiian: 7,
NewYork: 8
};
for (var pizzaType in prices) {
var inputElement = document.getElementbyId('count' + pizzaType);
var labelElement = document.getElementbyId('total' + pizzaType);
inputElement.addEventListener('change', function(event) {
var total = prices[pizzaType] * parseInt(event.target.value);
var formattedPrice = '\u20ac ' + total.toFixed(2);
labelElement.innerHTML = '';
labelElement.appendChild(document.createTextNode(formattedPrice));
}, false);
}
I chose to use an anonymous function instead of a named one, as this is the most common practice with event listeners.
Make a more generic function for calculating your price, like onNumPizzChange which takes the base element name, e.g. 'Margherita'. In this function, extract your element like
var inputElm = document.getElementById('count'+elmBase);
then set up your events by wrapping this function with another like so:
document.getElementById('numPizzaMargheritaCount').addEventListener('change', function(){ onNumPizzaChange('Margherita')}, false);
Does that make sense?
Good luck!
An array isn't the most efficient way to solve the problem. You'd be better off with a more generalised function that has the necessary information (the event, the price, and the ID of the element to display the price) as parameters. Then use an array of objects to initialise everything. Something like this:
var pizzas = [
{
pizza: 'margherita',
price: 7,
input: 'countMargherita',
label: 'totalMargherita'
},
{
pizza: 'pepperoni',
price: 10,
input: 'countPepperoni',
label: 'totalPepperoni'
}
]
function calculatePrice(e, price, label) {
var total = price * parseInt(e.target.value);
var formattedPrice = '\u20ac '+total.toFixed(2);
var outputElement = document.getElementById(label);
outputElement .innerHTML = '';
outputElement .appendChild(document.createTextNode(formattedPrice));
}
Then iterate over that pizzas array to bind everything up:
for(var i = 0, l = pizzas.length; i < l; i++) {
(function(pizza) {
document.getElementById(pizza.input).addEventListener('change', function(e) {
calculatePrice(e, pizza.price, pizza.label);
}, false);
})(pizzas[i]);
}
The above uses a closure to avoid issues due to JavaScript's variable scoping; i is scoped to the function scope since there isn't block-level scoping. Since the event handler is essentially a deferred action, the value of i when that executes will also be the last value of i if you don't use one.

extract elements from two arrays with same value

Hello I want to extract elements from both arrays with the same url .How can i loop these two arrays and get their content, because it gives me undefined for the news_url and i think it outputs twice the items in the console.
function geo(news_array,user_tweets){
console.log(news_array,user_tweets);
for (var x=0; x<user_tweets.length; x++) {
var user = user_tweets[x].user;
var date = user_tweets[x].date;
var profile_img = user_tweets[x].profile_img;
var text = user_tweets[x].text;
var url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
function second(user,date,profile_img,text,url){
for (var i = 0; i < news_array.length; i++) {
var news_user = news_array[i].news_user;
var news_date = news_array[i].news_date;
var news_profile_img = news_array[i].news_profile_img;
var news_text = news_array[i].news_text;
var news_url=news_array[i].url;
if (url==news_array[i].news_url) {
geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url);
}
}
}
function geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url) {
console.log(url,news_url);
}
}
The problem is
in news_tweets function, you add news_url to news_array. So you should call
news_array[i].news_url
in second function.
I modify your code as
news_url: (item.entities.urls.length > 0)?item.entities.urls[0].url : '' in news_tweets function
add close brace } for geo function and remove } from last
add new_array parameter to second function like second(user, date, profile_img, text, url,news_array);
Modify code can be tested in http://jsfiddle.net/rhjJb/7/
You have to declare some variables before the first for loop, so that they can be accessed in the scope of the second function. Try to replace your first for loop with the following code:
var user, date, profile_img, text, url;
for (var x=0; x<user_tweets.length; x++){
user = user_tweets[x].user;
date = user_tweets[x].date;
profile_img = user_tweets[x].profile_img;
text = user_tweets[x].text;
url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
Moreover, in the if of your second function, news_array[i].news_url isn't defined. Use if (url == news_url) instead.

Categories