I am new to using google Firebase. I have manage to add real time saving data function, but I wanted to save the data that i have. Please could someone direct me to the right path?
Here is the code in .JS file:
var btn = document.getElementById(btn);
var weight, height, measure, bmi, error ;
function calculate() {
var firebaseRef = firebase.database().ref();
firebaseRef.child("BMI").set("BMI Values");
weight = document.getElementById("weight").value;
height = document.getElementById("height").value;
error = "Please enter some values";
height /= 100;
height *= height;
bmi = weight/height;
bmi = bmi.toFixed(1);
if (bmi <= 18.4) {
measure = "Your BMI is " + bmi + " which means " + "you are Underweight";
} else if (bmi >= 18.5 && bmi <= 24.9) {
measure = "Your BMI is " + bmi + " which means " + "You are Normal";
} else if (bmi >= 25 && bmi <= 29.9) {
measure = "Your BMI is " + bmi + " which means " + "You are Overweight";
} else if (bmi >= 30) {
measure = "Your BMI is " + bmi + " which means " + "You are Obese";
}
if (weight === 0 ) {
document.getElementById("results").innerHTML = error;
} else if (height === 0){
document.getElementById("results").innerHTML = error;
}
else {
document.getElementById("results").innerHTML = measure;
}
if (weight < 0) {
document.getElementById("results").innerHTML = "Negative Values not Allowed";
}
}
To add the BMI data to the database, you do something like this:
weight = document.getElementById("weight").value;
height = document.getElementById("height").value;
error = "Please enter some values";
height /= 100;
height *= height;
bmi = weight/height;
bmi = bmi.toFixed(1);
firebaseRef.child("BMI").push({
weight: weight,
height: height,
bmi: bmi
});
Aside from (obviously) passing in the values you got from the HTML, this code calls push(), which generates a new unique location in the JSON every time it's called. That way the values you enter won't overwrite what's already there.
Note that HTML elements typically return value as a string. So you might still have to convert the weight and height to numbers after getting from the HTML element:
weight = parseFloat(document.getElementById("weight").value);
height = parseFloat(document.getElementById("height").value);
Finally: saving data to Firebase is pretty well covered in the Firebase documentation and in the Firebase codelab for web developers. I highly recommend you check those out. A few hours spent there, saves many questions down the line.
Related
This is actually my first beginner project. I wrote the whole code myself. It's about buying phones through 3 different methods. You can tell the program to automatically buy all phones and phone masks for all money you got, to manually buy one by one or to enter a number of phones and masks you wanna buy. Together with all that I set a number of phones and masks available at the stop together with user's bank balance.
The problem's coming from eraseData function. It simply doesn't work. Actually, the first part of it works but the second where I'm trying to reset my variables to their original value isn't working.
I have problems with using this editor to put in my code so I will use Pastebin.
const PHONE_PRICE = 150.00;
const MASK_PRICE = 50;
var bankBalance = 1983;
var aPhones = 11;
var aMasks = 11;
var boughtPhones = 0;
var boughtMasks = 0;
function eraseData(){
var bankBalance = 1800;
var aPhones = 11;
var aMasks = 11;
var boughtPhones = 0;
var boughtMasks = 0;
var check = false;
var quantity = 0;
document.getElementById("money").innerHTML = "Money left: $" + bankBalance;
document.getElementById("phones").innerHTML = "Amount of phones: " + boughtPhones;
document.getElementById("masks").innerHTML = "Amount of phone masks: " + boughtMasks;
}
function updateData(){
document.getElementById("money").innerHTML = "Money left: $" + bankBalance;
document.getElementById("phones").innerHTML = "Amount of phones: " + boughtPhones;
document.getElementById("masks").innerHTML = "Amount of phone masks: " + boughtMasks;
}
checkOptions();
function checkOptions(){
var check = prompt("There is three different ways to buy a phone. (A)utomatically, (M)anually and by (Q)uantity. Choose one option.")
if(check == "A"){
buyPhoneA();
}
else if(check == "M"){
buyPhoneM();
}
else if(check == "Q"){
buyPhoneQ();
}
else{
alert("That's not a valid option!");
}
}
function buyPhoneA(){
alert("With this option you automatically spend all your money ($" + bankBalance.toFixed(2) + ") and buy all available phones and phone masks! (take in notice that you can't buy one if you don't have money for the other!)");
var check = prompt("Type I AGREE if you agree to use this option!");
if(check == "I AGREE" && aPhones >= 1 && aMasks >= 1 && bankBalance >= 200.00){
while(bankBalance >= PHONE_PRICE + MASK_PRICE){
aPhones--;
aMasks--;
boughtPhones++;
boughtMasks++;
bankBalance = bankBalance - PHONE_PRICE - MASK_PRICE;
updateData();
var check = false;
}
}
else{
alert("Something went wrong! Either you didn't type I AGREE correctly, we don't have phones left or you don't have enough money!");
console.log(aPhones + " phones left");
console.log(aMasks + " masks left!");
console.log(boughtMasks + " bought masks!");
console.log(boughtPhones + " bought phones!");
console.log(bankBalance + " money left in the bank");
checkOptions();
}
}
function buyPhoneM(){
alert("With this options we will ask your over and over again to buy a phone! You can decline or agree to buying a new one! No accessories included");
var check = prompt("Type I AGREE if you agree to do this option!");
if(check == "I AGREE" && bankBalance >= 150.00 && aPhones >= 1){
aPhones--;
boughtPhones++;
bankBalance = bankBalance - PHONE_PRICE;
updateData();
buyPhoneM();
var check = false;
}
else{
alert("Something went wrong! Either you didn't type I AGREE correctly, we don't have any phones left or you don't have enough money!");
checkOptions();
}
}
function buyPhoneQ(){
var quantity = 0;
alert("With this option you will be asked to input a number of phones and accessories you want to buy!");
var check = prompt("Type I AGREE if you agree to use this option!");
if(check == "I AGREE"){
var quantity = prompt("Input a number of how many phones and accessories you want to buy!")
if(bankBalance >= 200.00 && aPhones >= 1 && aMasks >= 1){
aPhones + aPhones - quantity;
aMasks = aMasks - quantity;
bankBalance = bankBalance - ((PHONE_PRICE + MASK_PRICE) * 2);
boughtPhones = boughtPhones + quantity;
boughtMasks = boughtMasks + quantity;
updateData();
var check = false;
}
else{
alert("Something went wrong! Either the message your typed is not a number, you don't have enough money, we don't have enough masks or phones!");
buyPhoneQ();
}
}
}
HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<p id="money">Money left: $1800</p>
<p id="phones">Amount of phones: 0</p>
<p id="masks">Amount of phone masks: 0</p>
<br><br>
<button onclick="eraseData();">Erase Data</button>
<script type="text/javascript" src="script.js"></script>
</body>
CSS's not really important for this..
(I don't remember why exactly put script tags below my button tag but I think it's because of something weird happening with my code, it didn't work until I did it that way )
I'd be grateful if anyone could help, thanks!
You have used global variable and local variables name same.
Either rename the function variable different from global variables or remove var ahead of function variable.
I am trying to make this print out the grades in the array that I created. I can get my for loop to cycle through all of the grades in the array but it only prints out the last grade. I have it set up to print the grade out each time the for loop completes one cycle, but as I said, it is only printing out the last grade. I also tried to use the .innerHTML but that did not work either as you will see in the code:
var arrayTest = [78, 65, 41, 99, 100, 81];
var arrayLength = arrayTest.length;
var midtermTest = 60;
var msg = "";
var grade;
arrayOfGrades();
addBonus();
function tellGrade() {
if (grade > 100) {
msg = "Grade is higher than 100!, " + grade;
}
else if (grade >= 90) {
msg = "You got an A " + grade + "!!, ";
}
else if (grade >= 80) {
msg = "You got a B " + grade + "!!, ";
}
else if (grade >= 70) {
msg = "You got a C " + grade + "!!, ";
}
else if (grade >= 60) {
msg = "You got a D " + grade + "!!, ";
}
else if (grade <= 59) {
msg = "You got a F " + grade + "!! :(, ";
}
else if (grade < 0) {
msg = "Grade is less than 0, " + grade;
}
}
function arrayOfGrades() {
for (var i = 0; i < arrayLength; i++) {
grade = arrayTest[i];
tellGrade(grade);
writeGrade();
}
}
function addBonus()
{
midtermTest = midtermTest + (midtermTest * .05);
grade = midtermTest;
tellGrade(grade);
writeMidtermGrade();
}
function writeGrade() {
//document.getElementById("test").innerHTML = "Test grade letter: " + msg.toString() + "<br />";
var el = document.getElementById('test');
el.textContent = "Test grade letter: " + msg.toString();
}
function writeMidtermGrade() {
var el = document.getElementById('midterm');
el.textContent = "Midterm test grade letter: " + msg.toString();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DecisionsAndLoopsAssignment1_Byrd</title>
<link href="css/default.css" rel="stylesheet" />
</head>
<body>
<div id="test">Missing grade!!</div>
<div id="midterm">Missing grade!!</div>
<script src="js/main.js"></script>
</body>
</html>
function writeGrade() overwrites whatever might already by in the elements it outputs to. So when called more than once only the last value is preserved. Using .innerHTML would do the same thing. Accumulating the content strings to a single var then making a single call to output them is one option to fix this.
I also note that you're passing temporary values around in global vars, which is generally considered poor form.
You are setting the ENTIRE content of the element not just adding on to it. This will constantly overwrite the work of the previous iteration of the loop, therefore you will only see the last result, cause computers are fast.
You have two options, read the textContent of the element, and continue adding to it. This concept is called self assignment.
var aMessage = "Hello, ";
aMessage += "World!";
console.log(aMessage") // => "Hello, World!"
Though general we would create a new element and append that element as a child
var msg = "A+"; // this should be a variable to our function vs a global va
function writeGrade() {
var el = document.getElementById('test');
var newEl = document.createElement("p");
newEl.textContent = "Test grade letter: " + msg.toString();
el.appendChild(newEl)
}
writeGrade()
<div id="test">
</div>
My problem is as followed: I want to realise a (really) small application in which I want to generate a letter (between A and E) and compare it with the user input made afterwards. If the user input is not the same as the generated letter a message should pop up, which tells the user that he made the wrong choice. If the user made the right choice, a counter gets +1 and if the user reaches at least 3 of 5 points, he wins a prize. The user has 3 tries before the script ends.
The hurdle is that my main focus lies on php. My knowledge in JavaScript is not that much.
So my script won't do anything when the user types his answer in.
SOLVED!
The Code beneath is the solution.
String.prototype.last = function(){
return this[this.length - 1]
}
;(function() {
var score = 0;
var text = "";
var possible = "ABCDE";
var noOfTries = 5;
function generateCharacter() {
var index = Math.floor(Math.random() * 100) % possible.length;
text = possible[index];
possible = possible.slice(0, index) + possible.slice(index+1);
alert(text);
return text;
}
function validate(string) {
return (string || "").trim().last() === text.last();
}
function handleChange(){
var valid = validate(this.value);
if(valid){
score++;
alert("Richtig!");
}else{
alert("Das war leider falsch. Die richtige Antwort wäre " + text + " gewesen!");
}
console.log(this.value.length === noOfTries)
this.value.length === noOfTries ? notify() : generateCharacter();
}
function notify(){
if(score == 0) {
alert("Schade! Sie haben " + score + " Punkte erreicht! Nochmal?");
}else if(score >= 1 && score <3){
alert("Schade! Sie haben lediglich " + score + " von 5 Punkten erreicht! Nochmal?");
}else if(score >= 3 && score <= 5) {
alert("Herzlichen Glückwunsch! Sie haben " + score + " von 5 Punkten erreicht!");
}
}
function registerEvent(){
document.getElementById('which').addEventListener('keyup', handleChange);
}
registerEvent();
generateCharacter();
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="which">Antwort? </label>
<input type="text" name="which" id="which" placeholder="#" style="width: 9px;">
And here's the fiddle: Compare generated string with user input
Having technical issues with this line of code.
I want it to first calculate the BMI than determine if weight is over 25 tell patient that
they are overweight. If under 18.5 they are underweight.
Cant Seem To get the function right.
var calculate
var test;
calculate = document.getElementById("answer");
calculate.innerHTML = (weight/(height*height))* 703;
if(calculate > 25)
{
calculate = document.getElementById("answer06");
calculate.innerHTML = "you are fat";
}
else if(calculate < 18.5)
{
calculate = document.getElementById("answer06");
calculate.innerHTML = "you are to skinny";
}
var bmi = (weight/(height*height))* 703;
calculate.innerHTML = bmi;
if(bmi > 25)
Update:
var bmi = (weight/(height*height))* 703;
document.getElementById("answer").innerHTML = bmi;
if (bmi > 25)
{
document.getElementById("answer06").innerHTML = "you are fat";
}
else if (bmi < 18.5)
{
document.getElementById("answer06").innerHTML = "you are too skinny";
}
Hello I am trying to get this program to add ALL of the total costs that accumulate throughout this loop. But the program keeps printing the most recent cost rather than all of the products that have been "purchased". Here is my code: `
var Customer_Name, Discount, Product="", Price, Quantity="", Cost ;
var blanket_price = 25;
var lotion_price = 60;
var surfboard_price = 60;
var sunscreen_price = 60;
var Customer_Name = prompt("Welcome to Jersey Shore Inc.! What is your name?","Type Name Here");
alert("Hello "+Customer_Name+", Please look through all available products and services before placing your order.");
do
{
Product= prompt("What product would you like?","Type Product Name Here");
Quantity= prompt("How much of the "+Product+" would you like?","Type Quantity Here");
var Total_Cost;
var SumOrderTotal=0;
if (Product == "blanket")
{
alert("You received a 50% discount! Click okay to see your receipt below.");
Total_Cost= 0.5*(Quantity*blanket_price);
Cost=(Quantity*blanket_price);
Discount = .50*blanket_price;
}
else if (Product == "lotion")
{
alert("You received a 50% discount! Click okay to see your receipt below.");
Total_Cost= 0.5*(Quantity*lotion_price);
Cost=(Quantity*lotion_price);
Discount = .50*lotion_price;
}
else if (Product == "surfboard")
{
alert("You received a 50% discount!Click okay to see your receipt below.");
Total_Cost= 0.5*(Quantity*surfboard_price);
Cost=(Quantity*surfboard_price);
Discount = .50*surfboard_price;
}
else if (Product == "sunscreen")
{
alert("You received a 50% discount! Click okay to see your receipt below.");
Total_Cost= 0.5*(Quantity*sunscreen_price);
Cost=(Quantity*sunscreen_price);
Discount = .50*sunscreen_price;
}
if((Product=="blanket" || Product=="sunscreen" || Product=="lotion" || Product=="surfboard"))
{
document.write("The cost of buying " + Quantity+ " of " + Product + " is $ "+ Cost +". </br>");
document.write("The discount for this purchase is $ "+Total_Cost+". <br/>");
}
else
{
alert("Sorry "+Customer_Name+" you entered an invalid product.(Refer to table for our products) Please Refresh the page to reload and place a new order.");
}
var SumOrderTotal = Total_Cost + SumOrderTotal;
var user_answer=confirm("Would you like to continue purchasing products?");
}
while(user_answer==true);
document.write("Thank you for placing an order with us, " +Customer_Name+". <br/>");
document.write("Your total order cost is $"+ SumOrderTotal+ ". <br/>");
`
move SumOrderTotal outside of do...while.
Like so:
var SumOrderTotal=0;
do {
Product = prompt("...");
Quantity = prompt("...");
var Total_Cost;
} while (...) {
...
}
Because you are initializing to 0 each time you start the cycle(do..while).