Well, my code have been working fine and I'm simply trying to make a simple game, until I added this (due to that I wanted to learn how to save the info to the users local storage):
if(localStorage.getItem('money'))
{
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="EXISTS";
} else {
localStorage.setItem('money', 0);
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="DOES NOT EXIST";
}
My full code looks like this:
<head><meta charset="UTF-8"></head>
<body><span id='test'></span>
Generated something: <span id='money'>0$</span> (money per click: <span id='MPC'>1$</span>)
<br />
Upgrade 1 upgrades: <span id='u1Us'>0</span> (production rate: <span id='u1Pr'>0</span>)
<br />
<span id='updates'></span>
<br />
<button onClick='mButton()'>Generate something.</button>
<br /><br />
<b>Upgrades:</b>
<br /><br />Generator upgrades:<br />
<button onClick='buyU1()'>Buy upgrade 1. ($30)</button>
<br /><br />Self-generated upgrades:<br />
<button onClick='buySG1()'>Buy Self-Generated Upgrade 1 ($500)</button>
</body>
<script>
if(localStorage.getItem('money'))
{
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="EXISTS";
} else {
localStorage.setItem('money', 0);
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="DOES NOT EXIST";
}
var U1Amount = 0;
var cMoney = 1;
function mButton()
{
Money += cMoney;
document.getElementById('money').innerHTML=Money + "$";
}
function buyU1()
{
if(Money < 30)
{
document.getElementById('updates').innerHTML="You do not have enough money.";
resetUpdates();
} else {
Money -= 30;
U1Amount += 1;
document.getElementById('u1Us').innerHTML=U1Amount;
document.getElementById('money').innerHTML=Money + "$";
document.getElementById('updates').innerHTML="You have successfully bought Upgrade 1";
var calcU1Amount = U1Amount * 5;
document.getElementById('u1Pr').innerHTML=calcU1Amount;
resetUpdates();
}
}
var interval = setInterval(gMoneyU1, 1000);
function gMoneyU1()
{
var calc = 5 * U1Amount;
Money += calc;
document.getElementById('money').innerHTML=Money + "$";
}
function buySG1()
{
if(Money < 500)
{
document.getElementById('updates').innerHTML="You do not have enough money.";
resetUpdates();
} else {
Money -= 500;
cMoney += 1;
document.getElementById('MPC').innerHTML=cMoney + "$";
document.getElementById('money').innerHTML=Money;
}
}
function resetUpdates()
{
setTimeout(function(){document.getElementById('updates').innerHTML="";}, 10000);
}
</script>
I'm going to add the localStorage to all info that I want to save, but I'm having problems with the first one so yer.
What my code WITH my save-the-persons-info outputs is: http://puu.sh/6iONl.png (and it keeps on in all eternally)
It keeps adding '0' for some reason and I can't figure out why. I'd really appreciate help.
Thanks in advance.
Sorry if my code is messy, I'm still learning, hence why asking for help.
The only time that you ever set to localStorage is when you call localStorage.setItem('money', 0);.
You probably want to change that to setting the real value of the money variable.
Local storage stores everything as a string, so you'll want to call parseInt() on whatever you get back from local storage. Then, you should be able to properly add two ints together, rather than concatenating two strings together.
The values in localStorage are all strings. When you do:
localStorage.setItem('x', 0);
var x = localStorage.getItem('x'); // x === '0'
x = x + 1; // x = '01';
the thing you set in local storage will be the value you gave converted to a string. You should parseInt (or convert it some other way back to a number) when you retrieve it from localStorage to avoid this problem.
Your if statement will always return false so you'll never get to the "if true" part of your if statement. This is because the local storage value will either be null if not set, or a string value ("0") on most browsers if set, or an integer on some browsers if set. (Most browsers will only maintain strings for local storage, although the HTML5 specs do allow for other values.)
So first, of you would need to change the if part to something like this:
if (localStorage.getItem('money') != null)
I'm not completely sure what you're trying to achieve logic-wise but as mentioned, your other issue is that you're only setting the value to 0 and then reading the value right after (which would be zero still.) This is why you're getting zeros.
Related
I am currently having a problem displaying a calculated sum on the next page in javascript/html.
My calculation for defining the sum looks like this, where the 'sum + €' is displayed at the end.
function udregnPant() {
let sum = 0;
for (i = 0; i <= pantListParsed.length; i++) {
let totalPantKr = pantListParsed[i].aPantMoney + pantListParsed[i].bPantMoney + pantListParsed[i].cPantMoney;
sum += totalPantKr;
console.log(sum);
document.getElementById('sumAfPantB').innerHTML = sum + " €.";
}
}
In the following HTML input I want to display the sum as the value instead of '10 €'
<input type="text" name="amount" id="text1" value="10 €." readonly/>
Appreciate your help!
Make use of web storage.
sessionStorage - stores data for one session
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')
localStorage - stores data with no expiration date
localStorage.getItem('label')
localStorage.setItem('label', 'value')
Example
function setSum(value) {
localStorage.setItem("sum", value);
}
function getSum() {
return localStorage.getItem("sum");
}
Live Example at JS Bin
References
Share data between html pages
HTML5 Web Storage
After calculating your value, redirect the user to a URL with the value in the query string (See Redirections in HTTP) -- this may look something like
window.location = http://mysite/page2.html?amount=12
On the new page, retrieve the value from the query string using the searchParams property (see URL.searchParams). Could look something like:
let params = (new URL(document.location)).searchParams;
document.getByElementId('text1').value = params.get('amount');
Here is a little example using local Storage, since so doesnt allow local storage try it in jsfiddle and
the code sample as well:
document.getElementById('btnSend').onclick = ()=>{
let total = document.getElementById('txtTotal').value;
if(!isNaN(total) && total > 0){
localStorage.setItem('total', total);
document.getElementById('txtTotal').value = '';
}
}
document.getElementById('btnLastTotal').onclick = ()=>{
var lastTotal = localStorage.getItem('total');
if(lastTotal !=undefined){
alert('last total is:'+lastTotal);
}else{
alert('No records found');
}
}
<input type="text" id="txtTotal">
<br>
<input type="button" id="btnSend" value="Save the total"> <input type="button" id="btnLastTotal" value="get Last Total">
Hope it helps
This has to be super easy, just couldn't find the solution for the past three hours:
I want to display a number (100) on my website that will be increased by the days past, problem is that the number goes back to the 100 when I reload the website, how do I make that number stay increased over time?
Here's the code:
<script>
var smyle = 11406;
var happyclients = 1006;
var hours = 4220;
window.setInterval(
function () {
smyle = smyle + 2;
document.getElementById("smiles").innerHTML = smyle;
}, 2880);
window.setInterval(
function () {
happyclients = happyclients + 4;
document.getElementById("happy").innerHTML = happyclients;
}, 28800000);
window.setInterval(
function () {
hours = hours + 8
document.getElementById("hoursspent").innerHTML = hours;
}, 86400000);
</script>
The HTML
<div class="col-md-3 col-sm-6 animate-box" data-animate-effect="fadeInLeft">
<div class="feature-center">
<span class="icon">
<i class="ti-music"></i>
</span>
<span class="counter js-counter" data-from="0" data-to="" data-speed="4000" data-refresh-interval="50" id="smiles"></span>
<span class="counter-label">Smiles Created</span>
</div>
</div>
I am new to JS, previously tried with PHP but couldn't find the answer either, this is the closest I got.
So far I've gotten to this with your help, the idea of storing the data on the local database is quite clean and efficient, but I'm not being able to make it work yet (see changes at the bottom of the code)
I've read plenty of documentation about this and I think that the order is correct, but is it?
<script>
var smyle = 11000;
var happyclients = 1006;
var hours = 4220;
window.setInterval(
function () {
smyle = smyle + 2;
document.getElementById("smiles").innerHTML = smyle;
}, 288);
window.setInterval(
function () {
happyclients = happyclients + 4;
document.getElementById("happy").innerHTML = happyclients;
}, 288);
window.setInterval(
function () {
hours = hours + 8
document.getElementById("hoursspent").innerHTML = hours;
}, 864);
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("smyle");
//Retrieve
document.querySelector("smiles").innerHTML = localStorage.getItem("smyle");
} else {
document.write(11404);
}
</script>
I didn't change anything in the HTML part yet, so the id is still id="smiles"
You may wish to store this somewhere, which could be a cookie or more easily just store it in a database. You can say for each user how long they have spent, by updating your database every few seconds or minutes. Then all you would need to do is pull for that data and check where the data is.
Currently, your method requires the user to have the page open continuously, which will in fact restart it every time as the JavaScript will have no sense of previous time spent.
you can save it in localStorage on client side.
here is the reference
if you want the same result for everyone you should do this on your server.
Saving the data in localStorage will definitely help:
localStorage.setItem(//takes an object);
For retrieval:
document.querySelector("...").innerHTML = localStorage.getItem(//takes object key);
Why this isn't working?
I also did this by assigning the result back to the input field but that didn't work and still this is not showing an alert which should show the result..
<script type="text/javascript">
function calculate() {
var calculateit=document.getElementById('disp');
var pluscharacter=/+/;
var matchplus=calculateit.search(pluscharacter);
var inputlength=calculateit.length;
if(matchplus!=-1 && matchplus!=0 matchplus!=inputlength) {
answer=calculateit[0]+calculateit[1];
alert("Your answer is: "+answer+" Is it?");
}
}
</script>
Your if statement isn't a valid condition. Try:
if(matchplus!=-1 && matchplus!=0 && matchplus!=inputlength)
var calculateit = document.getElementById('disp');
var matchplus = calculateit.search(pluscharacter);
calculateit is a Node doesn't have any search() method.
You're doing stuff you don't need to do - just split the string. You also need to get the innerHTML - THAT's the string. Or you can get the "value" from an input field instead. I'd trim it to get rid of the white space around the equation, though the parseInt would take care of that as well. I'd also push the answer into another div. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/9ezky35v/2/
With this HTML:
<h3>Equation</h3>
<div id="disp">12+12</div>
<h3>Answer</h3>
<div id="answer"></div>
You can use this script:
function calculate() {
var calculateit = document.getElementById('disp').innerHTML.trim(),
numbers = calculateit.split('+'),
answerDiv = document.getElementById('answer');
if ( numbers.length > 1 ) {
answer = parseInt(numbers[0]) + parseInt(numbers[1]);
answerDiv.innerHTML = "Your answer is: <b>" + answer + "</b>, Right?";
} else {
answerDiv.innerHTML = "I can't calculate that equation.";
}
}
calculate();
And how do I get it to display the number, not undefined?
It's a tipping app. The user inputs the price of whatever it is they bought (pizza, haircut, etc.) in #price, then calcTip() calculates the tip, sends it over to calcTotal() which calculates the total, and sends it over to displayAmounts().
I don't know exactly what happens, but something messes up with the variable tip. calcTip() works correctly and calculates the tip amount successfully. I know this because the JavaScript console displays the amount when I input tip;. However, on the page, #tipSpan displays the tip as undefined.
What baffles me most is that the variable total works perfectly fine.
Does anyone know what might be going on or how I can fix it?
Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tipping App</title>
<style>
<!-- Temporary -->
#error {
display: none;
}
</style>
</head>
<body>
<div id="wrapper">
<header>
<h1>Tipping App</h1>
</header>
<section>
<div class="price">
<h2>Price Information</h2>
<label for="priceInput">Enter the price below!</label><input id="priceInput" type="text"><button id="calcButton">Calculate the Tip</button>
<p id="error">Error: You need to enter the cost!<br><br>Use only numbers and decimal points, no currency symbols or letters.</p>
</div>
<div id="tipContainer" class="tip">
<h2>Tip Information</h2>
<p id="tipPara">Your tip should be... <span>$<span id="tipSpan"></span></span></p>
</div>
<div id="totalContainer" class="total">
<h2>Total Information</h2>
<p id="totalPara">Your total is... <span>$<span id="totalSpan"></span></span></p>
</div>
</section>
</div>
<script src="js/app.js"></script>
</body>
</html>
Here is the JavaScript:
///// VARIABLES
//////////////////////////////
var priceInput = document.getElementById("priceInput");
var calcButton = document.getElementById("calcButton");
var error = document.getElementById("error");
var tipContainer = document.getElementById("tipContainer");
var tipPara = document.getElementById("tipPara");
var tipSpan = document.getElementById("tipSpan");
var totalContainer = document.getElementById("totalContainer");
var totalPara = document.getElementById("totalPara");
var totalSpan = document.getElementById("totalSpan");
var tip;
var total;
///// FUNCTIONS
//////////////////////////////
function calcTip() {
var price = priceInput.value; // This is the price the user inputs
var minTip = (Math.ceil(price * .15)); // Calculates a 15% tip rounded up to the nearest dollar
var maxTip = (price * .2); // Calculates a 20% tip
if (isNaN(price) || price === "") {
// If the user doesn't enter a number
// Or doesn't enter anything,
// Then display the error message
error.style.display = "block";
return;
} else {
error.style.display = "none";
if (maxTip < minTip) {
// If the 20% tip is less than the 15% rounded tip,
// Then let's go with that 20% tip
calcTotal(price, maxTip);
tip = maxTip;
} else {
// Otherwise, let's just do the 15%
calcTotal(price, minTip);
tip = minTip;
};
};
};
function calcTotal(price, tip) {
// Add the price and the tip together to yield the total
price = parseInt(price);
tip = parseInt(tip);
total = (price + tip);
displayAmounts();
}
function displayAmounts() {
// Update the page to display the tip and the total to the user
tipContainer.style.display = "block";
totalContainer.style.display = "block";
tipSpan.innerText = tip;
totalSpan.innerText = total;
}
///// EVENTS
//////////////////////////////
calcButton.addEventListener("click", calcTip);
Also, unrelated, but does my JavaScript look good? Is it clean code? I hope to find a web development job in the near future, and I know I need to be good at JavaScript.
WORKING DEMO
Update the function arguments
function calcTotal(price, maxTip) {
// Add the price and the tip together to yield the total
price = parseInt(price);
tip = parseInt(maxTip);
total = (price + tip);
displayAmounts();
}
Here the argument tip is overriding the global variable. Replace it to maxTip as you call.
1) In function displayAmounts, pass parameters tip & total
2) Instead of
tipSpan.innerText = tip,
TRY WITH
tipSpan.innerHTML = tip;
and same for total ,
use totalSpan.innerHTML = total
instead of
totalSpan.innerText ;
Then it should work
Try changing your method definition so it passes the values in:
displayAmounts(); should become displayAmounts(tip, total);
See the fiddle here.
Also you should use parseFloat rather than parseInt assuming you'll want to be more accurate than whole numbers.
Just a small mistake!
Instead of:
calcTotal(price, minTip);
tip = minTip;
Do:
tip = minTip;
calcTotal(price, minTip);
This way tip is calculated before displayAmounts is run.
Abut your code:
This is fine with just getting started. I recommend going through w3school's tutorials on javascript. The more you use javascript, the better you will get.
If you want a learning path I would recommend taking, let me know.
innerText works only on IE. textContent is W3C-compliant, but if you want your code to be standards compliant and cross-browser safe you should use this:
while( tipSpan.firstChild ) {
tipSpan.removeChild( tipSpan.firstChild );
}
tipSpan.appendChild( document.createTextNode(tip) );
Do this for totalSpan also.
I'm trying to make a game in javascript. I still have many issues in the code. The code is supposed to have 2 buttons; one for shuffling images dice and a button to check if the kid wrote the correct answer or not.
2 buttons
1 textbox
and a place to show the answer if it's correct or not
Here is my code.
I don't know why when I put the source of document.getElementbyID("test") it shows nothing
because I want every time I click on start a random image is selected.
I would appreciate any help as I am still a beginner in javascript.
<head>
<script type="text/javascript">
function startf(){
var images = [];
index = 0;
images[0] = "<img src='1.png' length=70px width=75px>";
images[1] = "<img src='2.png' length=70px width=75px>";
images[2] = "<img src='3.png' length=70px width=75px>";
images[3] = "<img src='4.png' length=70px width=75px>";
index = Math.floor(Math.random() * images.length);
take(index);
function take(ind)
{
return document.getElementbyId("ind")="What should i put here";
}
}
function check(){
var ch=getElementbyId("answer").value;
if (ch=index+1)
{
document.getElementbyId.innerHTML="TRUE";
}
else
{
document.getElementbyId.innerHTML="False";
}
}
</script><br>
</head>
<img id="test" src="" alt="..." length="75px" width="75px" />
<body>
<input type="button" value="start" onclick="startf()">
<input id="answer" type="text" name="checkvalue" value="Enter Value" onclick="check()">
<div id="fa">
</div>
<input type="button" value=chek onclick="check()">
</body>
1- Put and end to each instructions --> ;
2- Do not use document.getElementById directly, there will be at least one occurence with an error into it and you don't want that.
function _e(id) {
return document.getElementById(id);
}
3- Always put brackets and (...) around your IF-ELSE blocks:
if (...) {
//....
} else {
//....
}
4- Every tag attributes should have " " around their values, for example:
<input type="button" value="start" onclick="check()" />
5- You could only put image paths in your array since it seems to be what needs to be updated in #test image.
It is document.getElementById check the casing. Your check function is wrong... you can't assign a value to document.getElementById function. Also your if is wrong. Do you know any JavaScript?
I'm guessing what you want is probably something like this. You seem to be trying to add or replace an element just by using document.getElementById(id) = something but that's not how it works. Instead, to change an image to another file you need to alter its src attribute. (There are other ways but this is maybe the simplest.)
// Declare the variable called number here so it can be accessed
// by all of the following functions.
var number;
// a simple function to save typing document.getElementById all the time
function _e(id) {
return document.getElementById(id);
}
function startf() {
// Pick a number between 1 and 4
number = Math.floor(Math.random() * 4 + 1);
// Set the image with id 'test' to have the source 1.png, 2.png etc.
_e('test').src = number + '.png';
}
function check() {
// note that == is used for comparison, = is used for assignment
if (_e('answer').value == number) {
_e('fa').innerHTML = "TRUE";
}
else {
_e('fa').innerHTML = "False";
}
}