Javascript LocalStorage Setting Other Variables to Null - javascript

I have a program that calculates ticket quantities. If I set a new value to a variable using local storage it will cause the other variables to go null. But if I set the value of every variable in the form then nothing will be null and there are no issues, but the problem is I don't want the user to have to set the values of every variable everytime they want to set the value of one variable. How can I rewrite this code so that the other variables won't go to null if one variable is changed? Currently I only have it setup for beforenoonprice and matineeprice, but will add the rest once this issue is resolved.
var beforenoonprice = 6.75; // CHANGE THE PRICE OF THE BEFORE NOON TICKET
var matineeprice = 9.00; // CHANGE THE PRICE OF THE MATINEE TICKET
var seniorprice = 9.25; // CHANGE THE PRICE OF THE SENIOR TICKET
var militaryprice = 9.25; // CHANGE THE PRICE OF THE MILITARY TICKET
var studentdayprice = 8.00; // CHANGE THE PRICE OF THE STUDENT DAY TICKET
var seniordayprice = 6.75; // CHANGE THE PRICE OF THE SENIOR DAY TICKET
var adultprice = 10.75; // CHANGE THE PRICE OF THE ADULT TICKET
var childprice = 8.00; // CHANGE THE PRICE OF THE CHILD TICKET
var threeDprice = 3.50; // CHANGE THE PRICE OF THE REGULAR 3D PRICE
var imaxPrice = 4.50; // CHANGE THE PRICE OF THE IMAX TICKET
var imax3dPrice = 5.50; // CHANGE THE PRICE OF THE IMAX 3D TICKET
var output = document.getElementById('output');
function updatePricingFunction()
{
var beforeNoonFieldChange = document.getElementById('beforeNoonNPSlot').value;
var matineeFieldChange = document.getElementById('matineeNPSlot').value;
localStorage.setItem('text', beforeNoonFieldChange);
localStorage.setItem('text1', matineeFieldChange);
}
function load(){
var storedValue = localStorage.getItem('text');
var storedValue1 = localStorage.getItem('text1');
beforenoonprice = storedValue;
matineeprice = storedValue1;
beforeNoonCPSlot.innerHTML = "$" + parseFloat(storedValue).toFixed(2);
$("#beforeNoonPrice").attr = parseFloat(storedValue).toFixed(2);
$('#beforeNoonPrice').append("$" + (storedValue * 1).toFixed(2));
matineeCPSlot.innerHTML = "$" + parseFloat(storedValue1).toFixed(2);
$("#matineePrice").attr = parseFloat(storedValue1).toFixed(2);
$('#matineePrice').append("$" + (storedValue1 * 1).toFixed(2));
}

Related

How to retrieve a value from a variable outside of a condition?

I'm learning JS, but I don't know if it's possible to do what I want to achieve.
I have a variable named btcVariationTotal which is in a condition, and I want to retrieve the value of this variable in another variable called tmp, but this variable is not included in the condition.
My problem is that tmp always shows me 0. I don't understand why? And how can I solve this problem, please?
I really want to retrieve the value outside the condition.
console.clear();
let wsBtc = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade');
let btcStockPriceElement1 = document.getElementById('btcValue1');
let btcStockPriceElement2 = document.getElementById('btcValue2');
let btcLastPrice = null;
let btcStockObject = null;
wsBtc.onmessage = (event) => {
btcStockObject = JSON.parse(event.data);
};
let btc1 = 0, btc2 = 0;
let btcVariation_1_2 = 0;
let btcVariationTotal = 0;
let tmp = 0;
let btcRunTimers = setInterval(() => {
let minutes = new Date().getMinutes();
if (minutes === 51) {
let val1 = parseFloat(btcStockObject.p).toFixed(1);
let price = parseFloat(btcStockObject.p).toFixed(1);
btcStockPriceElement1.innerText = price;
btcStockPriceElement1.style.color =
!btcLastPrice || btcLastPrice === price
? 'black'
: price > btcLastPrice
? '#AAFF00'
: 'red';
btcLastPrice = price;
btcStockObject = null;
btc1 = val1;
}
if (minutes === 52) {
let val2 = parseFloat(btcStockObject.p).toFixed(1);
let price = parseFloat(btcStockObject.p).toFixed(1);
btcStockPriceElement2.innerText = price;
btcStockPriceElement2.style.color =
!btcLastPrice || btcLastPrice === price
? 'black'
: price > btcLastPrice
? '#AAFF00'
: 'red';
btcLastPrice = price;
btcStockObject = null;
btc2 = val2;
btcVariation_1_2 = ( (parseFloat(btc2) - parseFloat(btc1)) / btc1 * 100);
document.getElementById("btcResult1").innerHTML = btcVariation_1_2.toFixed(2);
}
btcVariationTotal = (parseFloat(btcVariation_1_2));
console.log("btc variation => " + btcVariationTotal);
document.getElementById("result").innerHTML = btcVariationTotal.toFixed(2);
tmp = btcVariationTotal;
}, 60000);
console.log("tmp => " + tmp);
The good news is that you are in fact doing what you want: you are retrieving
the value of the btcVariationTotal variable, and storing in tmp, which is
defined in the outer scope, outside of your setInterval callback.
The only problem you have is that you can't display a modified tmp, and
that's because you only call console.log before setting tmp, you never
call it after it has been changed. User Ivar has tried to explain that in
the comments, maybe I can detail it a bit more:
At time t=0, you set tmp = 0, you set your timers with setInterval, associating
a callback function (which does NOT run at this point), and then you call
console.log to display tmp (it's 0, because no callback has ever run).
At time t=60s, your callback runs, sets btcVariationTotal to some value, and
assigns that to tmp. No attempt is made to display the tmp value. Then this
gets repeated every 60s.
So what's missing is for you to write some code that displays the tmp value
after it has been changed. One way to do that, is to put that code inside
some other callback and arrange for it to be called. I suggest a simple
button. Add the following somewhere in your html page:
<button id="show-tmp">Show tmp</button>
Add the following lines at the end of your JS code:
let btn = document.getElementById('show-tmp');
btn.onclick = function() {
console.log(`tmp: ${tmp}`);
}
Now clicking on the button will show you the value inside tmp; if you do it
before the first 60 seconds, it will show 0; if you do it afterwards, it will
show whatever value was in btcVariationTotal.

How to make value auto update when input numbers are changed in javascript?

Here is a link to the tip calculator - it's hosted on netlify.
I created a tip calculator using html, scss, javascript. no tutorials used, so I'm pretty proud. It took me waaayyyyy longer than I had planned on, but it's done. needless to say, I am a complete beginner.
In any event, I need some help.
I need to know how to make the numbers auto-update if I input a new dollar amount into the billing input.
For instance, if the bill is $50, and the tip percent is 50% that's a $25 tip Amount. for a total bill of $75 dollars.
But let's say I mistyped the bill, so I go back to put in $60, 50% of $60 is $30. so the total bill amount should auto-update to $90. But I can't figure out how to get all of that to happen instantaneously when I change the dollar amount in the billing input.
I have a feeling that it has something to do with using a "change" event listener. but I don't understand how to best implement it, or if that's even the answer here.
// Upper Box Selections
const tipPercent = document.querySelector(".tip-percent");
const tipSlider = document.querySelector("#tip-slider");
tipSlider.oninput = function () {
billInput = Number(document.querySelector("#bill-amt").value);
tipPercent.innerHTML = this.value + "%";
//Discovered that number input type still returns a string
//You can wrap multiple variables in parenthesis in order to append methods
let tipAmount = document.querySelector(".tip-amount");
// if a variable is referenced but not defined, it will be added to the window element - can now use in second function
tipTotal = Number((billInput * Number(this.value / 100)).toFixed(2));
tipAmount.innerHTML = "$" + tipTotal.toFixed(2);
const billTotal = document.querySelector(".bill-total");
billForSplit = Number(billInput + tipTotal).toFixed(2);
billTotal.innerHTML =
"<strong>$</strong>" + "<strong>" + billForSplit + "</strong>";
};
// Bottom Box Selections
// -Grab slider value
const splitSlider = document.querySelector("#split-slider");
splitSlider.oninput = function () {
// -Grab split person value-split PERSON for 1, people for more than 1
const splitPeople = document.querySelector(".split-people");
if (splitSlider.value <= 1) {
splitPeople.innerHTML = splitSlider.value + " person";
} else {
splitPeople.innerHTML = splitSlider.value + " people";
}
// -grab tip per person value
const splitTip = document.querySelector(".split-tip");
// -grab total bill per person value
const splitTotal = document.querySelector(".split-total");
// - tip per person equals tipTotal / split slider value
splitTip.innerHTML = "$" + (tipTotal / splitSlider.value).toFixed(2);
// -total bill/person = billTotal / splitSlider.value
splitTotal.innerHTML =
"<strong>$</strong>" +
"<strong>" +
(billForSplit / splitSlider.value).toFixed(2) +
"</strong>";
};
https://wonderful-meninsky-e0b1c7.netlify.app/
You should declare the function with a name like calcTotal() which will be run every time there is an input for the bill and tip:
const tipPercent = document.querySelector(".tip-percent");
const tipSlider = document.querySelector("#tip-slider");
function calcTotal() {
billInput = Number(document.querySelector("#bill-amt").value);
tipPercent.innerHTML = this.value + "%";
//Discovered that number input type still returns a string
//You can wrap multiple variables in parenthesis in order to append methods
let tipAmount = document.querySelector(".tip-amount");
// if a variable is referenced but not defined, it will be added to the window element - can now use in second function
tipTotal = Number((billInput * Number(this.value / 100)).toFixed(2));
tipAmount.innerHTML = "$" + tipTotal.toFixed(2);
const billTotal = document.querySelector(".bill-total");
billForSplit = Number(billInput + tipTotal).toFixed(2);
billTotal.innerHTML =
"<strong>$</strong>" + "<strong>" + billForSplit + "</strong>";
};
tipSlider.oninput = calcTotal;
document.querySelector("#bill-amt").oninput = calcTotal;

assigning values to properties in constructor function

I am working on an assignment for a JS course.
Instructions say to:
setHrs() function takes input of hours worked. function should save input to its instance variable name hrs. no returns.
Okay, so I am pretty much stuck. Below is my code, where I define the employees, give them properties, share those properties between Employee --> Employee1 --> Employee2
Once I got Employees sorted out, I need to create functions within Hourly() that I can then call on later in the program; getRate() and getHrs().
I need pointers for assigning new values to this.rate and this.hrs, here is my code:
//Prince of Wales, Bed and Breakfast Resort
function Employee(id, name, hiredate, position){
this.id = id;
this. name = name;
this.hiredate = hiredate;
this.position = position;
}
Employee.prototype.hired = "Employed";
var Employee1 = new Employee("4", "Blackadder",
"06-03-1902", "butler");
var Employee2 = new Employee("5", "Baldrick",
Employee1.hiredate, "who knows");
// printed out to test prototype works... everything above can be printed
function Hourly(rate, hrs) {
this.rate = 0;
this.hrs = 0;
this.setHrs = function(){
// set Employee1 hours
// set Employee2 hours
}
this.setRate = function() {
// set Employee1 rate
// set Employee2 rate
}
}
Hourly.prototype = new Employee();
Employee1.prototype.hrs = 50;
Employee2.prototype.hrs = 25;
Employee1.prototype.rate = 4;
Employee2.prototype.rate = 1;
console.log(
"Name : " , Employee1.name ,
" Hourly Rate : ", Employee1.setRate(),
" Hours Worked : ", Employee1.setHrs(),
);
console.log(
"Name : " , Employee2.name ,
" Hourly Rate : ", Employee2.setRate(),
" Hours Worked : ", Employee2.setHrs(),
);
I had thought of something else that might work, it doesn't, but I might be on the right track???
this.setHrs = function(){
Employee1.hrs = 50;
Employee2.hrs = 25;
}
this.setRate = function() {
Employee1.rate = 4;
Employee2.rate = 1;
}
I have also thought, maybe rate and hrs should be arrays and I can push values to them, but everything I tried didn't add values to the arrays. Plus, if I do that then when I print the array, I could end up with more problems.
SOLUTION EDIT:
function Employee(id, name){
this.id = id;
this. name = name;
} // end of employee()
function Hourly(id, name) {
Employee.call(this,id,name);
var rate = 0.0;
var hrs = 0.0;
this.setHrs = function(time){ this.hrs = time; }
this.setRate = function(pay) { this.rate = pay; }
My main issue may have been the variable set up. I thought I understood prototypal inheritance, but there were some small details that caused my code not to run. once I changed my code from
this.rate = rate;
this.hrs = hrs;
to
var rate = 0;
var hrs = 0;
it was pretty much smooth sailing from there. Additionally, I needed to call the previous function Employee(). My employee variables are defined later in the code, but they are pretty much set up the same except for one important change... calling the appropriate function.
var Employee1 = new Hourly("2262124", "Blackadder");
Employee1.setHrs(50);
Employee1.setRate(4);
Employee1.getPayCheck();
console.log(" ");
previously, I called Employee() and that worked for assigning values to name and id, but not for setting rate and hrs which are "further" down in the inheritance chain. I then passed ALL properties to the Hourly() function and my properties were getting their values appropriately.
I just wanted to post my solution here for others who may be having issues practicing with inheritance. Thank you for reading and commenting!!
The setter functions need to take a parameter, and then they should update the property of the current object.
this.setHrs = function(hours){
this.hrs = hours;
}
You shouldn't be accessing Employee1 and Employee2 inside the methods, because the caller can have other variables containing these objects. They use those variables when they call the method:
Employee1.setHrs(50);
Employee2.setHrs(25);
Part of the problem was also the , instead of + in console.log
function Employee(id, name, hiredate, position){
this.id = id;
this. name = name;
this.hiredate = hiredate;
this.position = position;
this.rate = 0;
this.hours = 0;
}
Employee.prototype.hired = "Employed";
Employee.prototype.setHrs =function(hours){
this.hours = hours;
}
Employee.prototype.setRates = function(rates){
this.rate = rates;
}
function Hourly (employeeContext,hours, rates){
employeeContext.setRates(rates);
employeeContext.setHrs(hours);
}
var Employee1 = new Employee("4", "Blackadder",
"06-03-1902", "butler");
var Employee2 = new Employee("5", "Baldrick",
Employee1.hiredate, "who knows");
//calling Hourly
Hourly(Employee1, 4, 25);
Hourly(Employee2, 1, 50);
console.log(
"Name : " + Employee1.name +
" Hourly Rate : " + Employee1.rate+
" Hours Worked : "+ Employee1.hours
);
console.log(
"Name : " + Employee2.name +
" Hourly Rate : "+ Employee2.rate+
" Hours Worked : "+ Employee2.hours
);
setHrs() function takes input of hours worked
You should be passing some parameters to this function. A setter function will take some input and "set" some object variable.
setHrs(hours)
You should do this for each Employee object you create.
Employee1.setHrs(50)
Employee2.setHrs(25)
I hope this helped.
EDIT
For clarification on what I meant:
If you were to create an Employee object like you already have
function Employee(id, name, hiredate, position){
this.id = id;
this.name = name;
this.hiredate = hiredate;
this.position = position;
}
Then you can instantiate Employees like this:
var johnSmith = new Employee("6", "John Smith", "04-28-2017", "Chef")
Now if we were to modify the Employee class like this:
function Employee(id, name, hiredate, position){
this.id = id;
this.name = name;
this.hiredate = hiredate;
this.position = position;
this.setHrs = function (hours) = {
this.hours = hours;
}
this.setRate = function (rate) = {
this.rate = rate;
}
}
Now you are able to instantiate the Employee object like I did above but now you can call these member functions on the object.
johnSmith.setHours(50);
johnSmith.setRate(25);
There are ways to handle inheritance if you had to handle both salary and hourly workers, but this solution will work if you only have to deal with hourly workers.

Why is my number coming up as 0? [duplicate]

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 6 years ago.
I am trying to make a calculator that calculates the amount of calories that have been burned in a certain amount of time, but whenever I run it, I get 0 as the output. I have tried setting the calorieCountOut variable to an arbitrary number, and then it works fine, but every time I run it with this code here, I get 0. Here is my code:
const AGECONST = 0.2017;
const WEIGHTCONST = 0.09036;
const HRCONST = 0.6309;
const SUBTRACTCONST = 55.0969;
const TIMECONST = 4.184;
//var gender = document.getElementById("gender").innerHTML;
var gender = "male";
var weight = document.getElementById("weight");
var age = document.getElementById("age");
var time = document.getElementById("time");
var hr = 140;//dummy number
function calculate(){
if (gender = "male"){
var calorieCount = ((age * AGECONST) - (weight * WEIGHTCONST) + (hr * HRCONST) - SUBTRACTCONST) * time / TIMECONST;
}
//else if (gender = "female"){
//}
var calorieCountOut = calorieCount.toString();
document.getElementById("output").innerHTML = calorieCountOut;
}
Try getElementById('myId').value for the value inside the control instead of the control itself as an object.
Right now you assign a html object to a variable, but what you want (i assume) is the number stored in that html object.

Keyup: add a value when a checkbox is checked

So I am using Keyup to calculate a total of input fields. So far so good.
But now I want to do this:
if checkbox #a is checked, add 12 to total amount. If not, add 0.
I based my code on this: http://jsfiddle.net/5xzSy/1/
$(document).keyup(function(){ // run anytime the value changes
var element1 = parseFloat($('#element1').val()) * 16.28 || 0; // get value of field and multiply by price
var total = 0+element1
});
How can I add the value of a checked checkbox and substract it if people uncheck it.
(Or even better: with a radiobutton?)
Thank you!
demo: http://jsfiddle.net/5xzSy/1079/ <-- updated (add 12 only if something is given, floatnumber)
btw: input is to be <input/> and not <input></input>
$('input').keyup(function(){ // run anytime the value changes
var firstValue = parseFloat($('#first').val()); // get value of field
var secondValue = parseFloat($('#second').val()); // convert it to a float
var thirdValue = parseFloat($('#third').val());
$('#added').html(firstValue + secondValue + thirdValue); // add them and output it
});
$('#check').on('change', function () {
var total = parseFloat($('#added').text()); // <-- update for float
if (total) {
if ($(this).is(':checked')) {
total = total + 12;
} else {
total = total - 12;
}
$('#added').text(total);
}
})
This should do it...
$(document).keyup(function(){ // run anytime the value changes
var element1 = parseFloat($('#element1').val()) * 16.28 || 0; // get value of field and multiply by price
var total = element1;
if ($('#a').is(':checked')) {
total = total + 12;
}
});

Categories

Resources