Enter age javascript error [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Can anyone tell me what's wrong with this specific code and how can I fix it? Thanks in advance.
<script language=javascript type="text/javascript">
toDays(21);
function toDays(years)
{
var time;
time = 365*years;
return time;
}
document.write("My age is " + time);
</script>

Document.write should be inside function or toDays(21) outside function
function toDays(years)
{
var time;
time = 365*years;
document.write("My age is " + time);
return time;
}
document.write("My age is " + toDays(21));
http://codepen.io/nagasai/pen/oLaRdw

The return value from the function was not stored in a variable.
Due to hoisting of the function in Javascript, the toDays is defined before its defination line.
Store the result from the function in a global variable time.
Use document.write to print the results.
var time = toDays(21);
function toDays(years)
{
var time;
time = 365*years;
return time;
}
document.write("My age is " + time);

Related

how to display something if the answer is 24 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I need to create an output that displays "that's correct" if the input is 24 and "wrong" if the input is something else.
This is a school project
<script>
function getText(id){
var text = document.getElementById(id).value;
return text;
}
function showReply(id, reply){
document.getElementById(id).innerHTML = reply;
}
function reply(){
var textFromUser = getText("myTextField");
var reply;
if (reply == "24") {
reply = "that is correct";
} else {
reply = "wrong"
}
showReply("output", reply);
}
</script>
This is what I have so far.
As I am a beginner pls forgive me for my sloppy code. thx in advance
function getText(id){
var text = document.getElementById(id).value;
return text;
}
function showReply(id, reply){
document.getElementById(id).innerHTML = reply;
}
function reply(){
var reply = getText("myTextField");
if (reply == 24) {
reply = "that is correct";
} else {
reply = "wrong"
}
showReply("output", reply);
}
<input type="text" id="myTextField" onkeyup="reply()">
<p id="output"></p>

Simple Javascript Quiz (trouble with global variables?)

I'm trying to make a simple javascript quiz, but its been difficult figuring out the scoring. I'm a beginner with javascript so bear with me. I'm creating a quiz that has a new question on a new page and the last page displays the score. Currently when I answer a question and go to the next page and the score resets. It's probably the variable I'm using but I don't know enough about javascript to fix it.
I have four buttons, one correct answer and three incorrect answers. The correct answer triggers and function that adds 1 to the variable x which is the score. The variable x is a global variable. So when I go to the next page to see the score the score resets at 0.
I'm trying to find a simple solution to this issue if possible. I condensed the code to one page for this post but the score is suppose to print the next page not the question page. Thank you to all who reads this!
var x = 0;
function myFunctionCorrect() {
x = x + 1;
document.getElementById("demo").innerHTML = "Correct!";
document.getElementById("scoretext").innerHTML = "Your score is " + x + ".";
}
function myFunctionWrong() {
document.getElementById("demo").innerHTML = "Wrong!";
}
<button onclick="myFunctionCorrect()" class="elementbutton">Spandrel</button>
<button onclick="myFunctionWrong()" class="elementbutton">Attic</button>
<button onclick="myFunctionWrong()" class="elementbutton">Roundrel</button>
<button onclick="myFunctionWrong()" class="elementbutton">Plinth</button>
<p id="demo"></p>
<p id="scoretext"></p>
var x = 0;
function myFunctionCorrect() {
x = x + 1;
localStorage.setItem("score", x);
}
function showScore() {
var score=localStorage.getItem("score")
document.getElementById("scoretext").innerHTML = "Your score is " + score + ".";
}
You have to do something like this your myFunctionCorrect should store the value in local-storage and then a function like showScore can retrieve the score from localstorage and show to user.
I don't see where your are moving to the next page, but javascript variables don't typically carry over from page to page, unless you were using frames or something and storing your JS in a parent frame.
Off the top of my head, I would persist the variables in the url, then parse then on the next screen.
If you were using a server-side language, I do it in a form instead.
I agree with everyone here on persisting the variables in the URL. I know you mentioned you're a beginner--even variables with global scope don't persist across different pages, so you can pass the score into the URL when the score updates, perhaps through the URL's hash:
function myFunctionCorrect() {
x = x + 1;
document.getElementById("demo").innerHTML = "Correct!";
document.getElementById("scoretext").innerHTML = "Your score is " + x + ".";
let scoreHash = `score:${x}`
window.location.hash = "scoreHash"
}
Then, when a new page loads, you can grab the hash from the referrer URL and re-declare it as your global x variable. So include this function at the top of your Javascript for each page:
var x;
document.onload = function() {
let previousScore = document.referrer;
x = previousScore
}

Creating a Script To Increase Numbers On Website [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
We have a website, on the front page we show "Parcels Shipped", we'd love the numbers to updated via a formula - i.e. we shipped 34,502,233 parcels in 2014... We show a static stat.... But we'd love to have the numbers increased via a formula that increases the number by the second/minute
Thanks for all the replies guys - So we current have this: gyazo.com/d421a3675884e2610d368c9e60e8acca
we want it to increase around 76 times per minute.... so a rotating number basically - i've no idea how to achieve this. (left number) & We want it to increase around 43 times per minute for middle number
Does anyone know where I can find this sort of trick?
This achieves your desired functionality using setInterval() to fire a function that checks to see how long it's been since today. Then, multiplying by the increase you mentioned in the comments and adding it to the numbers in your screenshot.
JS:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function timeSince() {
var prevTime = new Date(2015,8,8,0,0);
var thisTime = new Date();
return (thisTime.getTime() - prevTime.getTime()) / 1000;
}
function parcelCount() {
var secDiff = timeSince();
var leftNum = document.getElementById("left");
var midNum = document.getElementById("mid");
var leftNumCount = Math.round(((76/60) * secDiff) + 40093794);
var midNumCount = Math.round(((43/60) * secDiff) + 22874098);
leftNum.innerHTML = numberWithCommas(leftNumCount);
midNum.innerHTML = numberWithCommas(midNumCount);
}
parcelCount();
setInterval(parcelCount, 1000);
HTML:
<h3>Left</h3>
<span id="left"></span>
<h3>Mid</h3>
<span id="mid"></span>
Demo: http://jsfiddle.net/hopkins_matt/513ng07d/
Used info from these answers to build this:
https://stackoverflow.com/a/2901298/4556503
https://stackoverflow.com/a/6636639/4556503
Use setInterval with the increasing function as 1st argument and ms as the 2nd one.
var el = document.getElementById('counter')
var x = 0
window.setInterval(function(){
el.value = formula(++x)
}, 1000)
If the increase is completly random, just a "front-end design stuff" (sorry, guys), you can use setInverval() from Javascript.
It works this way:
every _s ms, the function will be called. If you have an increase factor, like a global constant you could do something like:
var myDiv = document.getElementById("myId");
var _mseconds = 1500; // mileseconds
var incFactor = 150;
var handlerInt = setInverval(function() {
myDiv.innerHTML = incFactor+incFactor; // you can use Math.Random() or something, instead
}, _mseconds);
Hope it helps!

Variable reset to default option, WHY? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I do not understand how I keep ending up with "null" after variable is assigned a number.
function evalKayScript(syn){
coms = extract(syn,"{...}");
document.write(JSON.stringify(coms));//debug
for(x in coms){
ops = extract(coms[x],"(...)");
com = null; //<-- ***com preset null***
for(y in funNames){
if(ops[1] == funNames[y]){
com = y; //<-- ***com changed to "y"***
}
}
alert(com); <-- alerts given below (first two alerts)
if(com == null){
alert("Command ((("+ops[1]+"))) Not Registered!");
return null;
}
exe = funValues[y];
inputs = execVars(ops[2]);
inputs = extract(inputs,"[...]");
for(y in inputs){
exe.replace(new RegExp("/\(\%"+y+"\%\)/gim"),inputs[y]);
}
exe.replace(new RegExp("/\(\%name\%\)/gim"),ops[0]).replace(new RegExp("/\(\%function\%\)/gim"),ops[1]);
exea = exe;
if(exe.replace(new RegExp("/\:\:\:javascript/gim"),"")! = exes){ //<-- new invalid ":" error
eval(exe);
}else{
evalKayScript(exe);
}
}
}
I do not understand why, variable "com" goes to a number, then back to null...
I have setup some error catching in my own form, and i end up with these alerts:
0 //<-- var com
null //<-- ***var com? this makes no sense, how does it go back to null?***
Command ((("(%name%) already exists!"))) Not Registered! //<--caused by if(com == null) This is normal.
Live script at http://jstone88.bugs3.com/kayscript/file1.html, and JS file at http://jstone88.bugs3.com/kayscript/kayscript.js
You aren't using RegExp constructor as it should have been used.
It is like this:
new RegExp("pattern without / at the beginning an end","flags");
/pattern/flags is literal form of writing a regex in js, but it is different in RegExp constructor.

Jquery/Javascript Issue [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm new to query/javascript and having a problem with the following code to calculate a gross value and tax amount based
on the net amount the user enters. The user will enter a double amount and the gross and vat amounts are also defined as doubles.
Can anyone help? I get an error: "Uncaught SyntaxError: Unexpected number" when i try running the following code.
$('#netPayment').change(calcLowerVatRateAndGrossAmount);
/* $('#netPayment').change(function(){
calcLowerVatRateAndGrossAmount();
}); */
});
function calcVatRateAndGrossAmount(){
var netPayment = parseFloat($('#netPayment').val());
var vatAmount = 00.0;
var VatRate = 20.0;
var grossPayment = 0.00;
var totalPaymentAmount = 0.00;
if (netPayment !== '') {
vatAmount = (netPayment * VatRate) / 100;
grossPayment = (netPayment - vatAmount);
$('#vatAmount').val(parseFloat(vatAmount.data).toFixed(2));
$('#grossPayment').val(parseFloat(grossPayment.data).toFixed(2));
} else {
$('#vatAmount').val(vatAmount.amountNull);
$('#grossPayment').val(grossPayment.amountNull);
}
};
So you calculate a number here
vatAmount = (netPayment * VatRate) / 100;
And in here, you treat vatAmount as an object that has a key data
$('#vatAmount').val(parseFloat(vatAmount.data).toFixed(2));
You should just be using the variable. A simple test
console.log("variable itself: ", vatAmount);
console.log("key data: ", vatAmount.data);
So you would need to just do
$('#vatAmount').val(vatAmount.toFixed(2));
$('#grossPayment').val(grossPayment.toFixed(2));
You do the same thing with grossPayment and you reference some other property vatAmount.amountNull
$('#vatAmount').val(vatAmount.amountNull);
$('#grossPayment').val(grossPayment.amountNull);
should be
$('#vatAmount').val(""); //or any error message
$('#grossPayment').val("");

Categories