I'm still new to coding and I'm trying to make a cookie clicker type game. I get
upgradecursor is not a function
when I run it on Chrome. I don't really understand the problem as I have a function called upgradecursor.
Pls help! :(
<!DOCTYPE html>
<html>
<head>
<title> Test </title>
<script>
//List of variables
var cookie = 0;
var cursor = 1;
var cursorupgradecost = 10;
function addcookie(){
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
cookie = cookie + cursor;
// Add one
currentValue = currentValue + cursor;
// Put it back with the new +1'd value
textField.value = currentValue;}
function upgradecursor(){
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
cookie = cookie - cursorupgradecost;
// Minus one
currentValue = currentValue - cursorupgradecost;
// Put it back with the new -10'd value
textField.value = currentValue;
//change the cost of the upgrade
cursorupgradecost = cursorupgradecost * 1.5;
//Upgrade the cursor
cursor = cursor + 1;
}
</script>
</head>
<body>
<script>
if (cursorupgradecost > cookie){
upgradecursor = false;}
else{
upgradecursor = true;}
</script>
<button type ="button" onClick = "upgradecursor()"/>Upgrade Cursor </button>
<input type="text" value="0" disabled name="lvl">
<br>
<button type="button" onClick="addcookie()"/>Add Cookie</button>
<input type="button" value="Cookies" disabled name="clicker">
<input type="text" value="0" id="textField" readonly/>
</body>
</html>
You are overwriting upgradecursor with a global variable after you include the JavaScript.
<script>
if (cursorupgradecost > cookie) {
upgradecursor = false;
} else {
upgradecursor = true;
}
</script>
This is the offending code. You need to rename this variable to something else to avoid overwriting the function.
Additionally, you should definitely avoid declaring global variables like this and look at making your code more encapsulated/modular.
--
Update based on your objective: If you want to only upgrade the cursor given a certain use case, then it might be useful to have a specific click handler that will run this check inside itself before calling upgradecursor. For example: -
function onCursorClick() {
if (cursorCost > cookie) {
// do something
} else {
upgradeCursor();
}
}
Notice how I have used camel casing to declare my functions and variables? Make sure you update your variable declarations to match my casing. This is common practice. You can read more on coding conventions here: W3Schools JavaScript Style Guide
I'd like to point out listeners should be attached via JavaScript (see DOM Event Listeners), but make sure you update the click handler to match our update, like so: -
<button type="button" onClick="onCursorClick()"/>Upgrade Cursor</button>
You have this:
if (cursorupgradecost > cookie){
upgradecursor = false;}
else{
upgradecursor = true;}
So while you started out by defining upgradecursor as a function, you overwrote it with a boolean before you ever called it.
The problem is here:
<script>
if (cursorupgradecost > cookie){
upgradecursor = false;}
else{
upgradecursor = true;}
</script>
What on earth is that supposed to even do?
Remove it and it should work.
Related
im just a beginner and i want to find the answer to this problem.
This is my html code.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type = "text" name = "step" id = "step">
<button onclick="myFunction()">Submit</button>
<p id = "demo"></p>
</body>
</html>
This is my javascript code.
var step = document.getElementById("step").innerHTML;
parseInt(step);
function matchHouses(step) {
var num = 0;
var one = 1;
while (num != step){
one += 5;
num++;
}
return one;
}
function myFunction(){
document.getElementById("demo").innerHTML = matchHouses(step);
}
What I did is to call the function matchHouses(step) by the click of the button. But the output is always 1. I also put parseInt to the step id as it is string but it is still doesnt work. I was expecting an output of 1+5 if the input is 1, 1+5+5 if the input is two and so on. How do I make it work?
The two key things are that a) parseInt won't do the evaluation "in place". It either needs to be assigned to a variable, or the evaluation done as you're passing it into the matchHouse function, and b) you should be getting the value of the input element, not the innerHTML.
Here are some additional notes:
Cache all the elements first.
Add an event listener in your JavaScript rather than using inline JS in the HTML.
No need to have an additional variable for counting - just decrement step until it reaches zero.
Number may be a more suitable alternative to parseInt which requires a radix to work properly. It doesn't always default to base 10 if you leave it out.
Assign the result of calling the function to demo's textContent (not innerHTML as it is just a simple string, and not a string of HTML markup.
// Cache elements
const step = document.querySelector('#step');
const demo = document.querySelector('#demo');
const button = document.querySelector('button');
// Add a listener to the button
button.addEventListener('click', handleClick);
function matchHouses(step) {
let out = 1;
while (step > 0) {
out += 5;
--step;
}
return out;
}
function handleClick() {
// Get the value of the input string and
// coerce it to a number
const n = Number(step.value);
demo.textContent = matchHouses(n);
}
<body>
<input type="text" name="step" id="step">
<button type="button">Submit</button>
<p id="demo"></p>
</body>
I rewrote your code like this:
let step = 0;
function handleInput(e){
step = e.value;
}
function matchHouses(step) {
var num = 0;
var one = 1;
while (num != step){
one += 5;
num++;
}
return one;
}
function myFunction(){
document.getElementById("demo").innerHTML = matchHouses(step);
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type = "text" name="step" id="step" onkeyup='handleInput(this)'>
<button onclick="myFunction()">Submit</button>
<p id = "demo"></p>
</body>
</html>
I have a problem with my function I made a if function in my addEventListener and when I click in the button it seems like the button take the value of the id="dollar" in the span, I don't know why and when I make a console log of the id="dollar", the browser show me the value of th input, I don't know why ?
With this code it seems like he only take the value of 1000 .
<div>
<p id="dollar">1000</p>
<input type="range" min="0" max="40000" step="100" value="0"
oninput="showDollar(this.value)" onchange="showDollar(this.value)">
</div>
<button id="bouton">OBTENER CREDITO</button>
<script type="text/javascript">
var nombre = document.querySelector('span').innerHTML;
var bouton = document.getElementById('bouton');
function showDollar(newDollar){
document.getElementById('dollar').innerHTML = newDollar;
}
bouton.addEventListener("click", function(){
if(nombre<750){
location.href = "https://www.google.com";
}
else{
location.href = "https://www.youtube.com";
}
});
</script>
in you're listenere you check the value of number but number is define only one time when the page is load.
Before test de value you need to update it :
bouton.addEventListener("click", function(){
nombre = document.getElementById('dollar').innerHTML
if(nombre<750){
location.href = "https://www.google.com";
}
else{
location.href = "https://www.youtube.com";
}
});
And i change
document.querySelector('span').innerHTML
by
document.getElementById('dollar').innerHTML
to retrieve the value of number, i think it was what you need
Below code is wrong
var nombre = document.querySelector('span').innerHTML;
You can getElementById or getElementByClass instead of querySelector;
Pretty new to this Javascript thing.
I want to change a Javascript variable when a user inserts a number into an input field in my HTML document and clicks a button.
I'm assuming you'd use a function, but how do you gather the data and change the variable?
The stuff I tried to make looks a little something like this.
HTML
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>
Javascript
var a = 0;
function changeTheVariable() {
a = document.getElementById("inputField").value;
}
but it's not working!
Edit 1:
Wow. I didn't think I'd get this kind of attention. I also found it a bit strange it didn't work at first.
The question I'm asking is partly for a calculator here: https://titomagic.com/debug
It's simple, you type in a number, click the button and it calculates (based on other variables) to a result on the bottom.
Here's a link to the Javascript file, if you wanna have a look: https://titomagic.com/js/bursdagskalkulator.js
To those of you asking; yes, I've been testing with a console.log and the variable is not changing. It's not affecting the other variables (as it should?).
Also I've never heard of JSfiddle.
I discovered few things in the summarizeGjester() function. First of all I moved all the Javascript code in the bursdagskalkulator.js file inside the summarizeGjester() function. Also I converted var antallGjester to integer using parseInt() function, because it was treated as string before.
var antallGjester = document.getElementById("gjesterAntallInput").value;
antallGjester = parseInt(antallGjester); //integer conversion
Also the first Boolean comparison was changed to
if ((antallGjester < 10) && (antallGjester > 0)), so that the second one would work if there’s 0 value: else if (antallGjester === 0).
function summarizeGjester() {
var antallGjester = document.getElementById("gjesterAntallInput").value;
antallGjester = parseInt(antallGjester);
var fastPris = 1500;
var fastPrisDifferanse = 10;
var gjestePris = 120;
var gjesteDifferanse = antallGjester - fastPrisDifferanse;
var gjesteSum = gjestePris * gjesteDifferanse;
var gjesterTotalt = 0;
if ((antallGjester < 10) && (antallGjester > 0)) {
console.log("antallGjester < 10");
gjesterTotalt = 1500;
} else if (antallGjester === 0) {
console.log("antallGjester === 0");
gjesterTotalt = 0;
} else {
console.log("else");
gjesterTotalt = fastPris + gjesteSum;
}
document.querySelector('#results').innerHTML = gjesterTotalt;
}
<form>
<div class="form-group">
<label for="gjesterAntall">Antall barn:</label>
<input type="number" class="form-control" id="gjesterAntallInput">
</div>
<button class="btn btn-lg btn-warning" onclick="summarizeGjester()" type="button" id="sumGjester">Legg sammen</button>
</form>
<h1 class="text-center" style="font-size:80px;"><strong><span id="results">0</span>,-</h1>
I hope this helps :-)
HTML
<input type="number" id="inputField" ClientIDMode="static">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>
Javascript
var a = 0;
function changeTheVariable() {
a = document.getElementById('inputField').value;
alert(a);
}
Use Static ClientIDMode for stable id and access after page rendering
PlaceHolders canh change childe's id
I suppose this will work for you
var a = 0;
function changeTheVariable() {
a = document.getElementById("inputField").value || a;
document.getElementById("result").innerText = parseFloat(a);
}
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe">Click me</button>
<div>Result: <span id="result"></span></div>
Edited:
The reason behind this code is not running in jsfiddle is here.
After making the changeTheVariable() global variable this code will work in jsfiddle also. Here https://jsfiddle.net/1b9cfmje/
Use the following javascript code:
window.onload = function(){ var a = 0; window.changeTheVariable = function() { a = document.getElementById("inputField").value || a; document.getElementById("result").innerText = parseFloat(a); }}
<script>
function checkName(){
var tmpName = document.getElementById("name");
if( tmpName.value.length == 0 ){
alert( "Name cannot be empty" );
return false;
}
else
return true;
}
function confirmForm( formObj ){
var nameBool = new Boolean();
var errorName = "";
nameBool = checkName();
if( nameBool == false )
errorName = "Invalid data in input name !";
return window.alert( "You have this error : \n " + errorName + "\n" + errorID );
}
</script>
<form name=reviewform onsubmit="return confirmForm(reviewForm)" method=POST >
<p>Name : <input type="text" id="name" ></p>
<p>ID : <input type="text" id="id" ></p>
<input type="submit" value="Click here!">
</form>
my problem is why my function cannot run ??? isn't something wrong? can any senior teach me where the place i wrong at??
i already editited and plus that form name and the function how it's work
i don't know isn't my implementation wrong or what
Both functions, though they need some work, and you clearly need to brush up on your JS knowledge, can run, you just have to call them. As it stands, you've just defined 2 functions. Nothing else.
Other issues, line/line:
//second line:
var tmpName = document.getElementById("name");
Here, you can't be sure this element is already leaded, perhaps the DOM isn't ready yet, so be careful, just wrap your entire code in a handler:
window.onload = function()
{
//your code here, this gets executed after the page is fully loaded
};
Next, don't think of JS as some sort of Java-for-browsers, it's a completely different animal. Stuff like:
var nameBool = new Boolean();
var errorName = "";
Is best written as declaring variables, but not assigning anything:
var nameBool, errorName;
If you want to be sure the nameBool is a boolean, just assign like so:
nameBool = !!checkName();//double bang
It also looks like you're trying to validate a form or handle a submit event of sorts. Why not use addEventListener for that? or, if you insist:
document.getElementById('formId').onsubmit = function(e)
{
//get event object:
e = e || window.event;
//this references form, as does (e.target || e.srcElement), you can access the elements it contains, and check them one by one
};
I am trying to remove the style or the background of a textbox to reveal the content after 10 clicks. How can I do that on Javascript?
here is my html:
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000">
and here is my JS:
function check() {
var tries++;
if (tries == 10){
document.getElementById('firstN').disabled= true;
}
}
The problem is that tries is a local variable (local to the check function). Every time check is called, a new variable named tries is created and initialized to 0.
Try this instead:
var tries = 0;
function check() {
tries++;
if (tries == 10) {
document.getElementById('firstN').style.background = '#ffffff';
}
}
(I'm assuming that you already have some code to call check when the element is clicked. If not, you need to add a click handler to your element.)
You are instantiating a var "tries" everytime you go into this function. Move the variable up a level to where it will increment:
var btn = document.getElementById("btnclick");
btn.onclick = check;
var tries = 0;
function check() {
tries++;
if (tries == 10){
var ele = document.getElementById("firstN");
ele.value= "DISABLED";
ele.disabled = true;
}
}
EDIT:
Working JSFiddle
store it in a cookie:
<script type="text/javascript">var clicks = 0;</script>
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" value="Click" onclick="clicks++">
onclick="$.cookie('clicks', $.cookie('clicks') + 1);"
Here you go. Remove the alert lines when you see that it works.
<html>
<head>
<title>Test</title>
<script>
function check(){
var getClicks = parseInt(document.getElementById('firstN').getAttribute('clicks')); //Get Old value
document.getElementById('firstN').setAttribute("clicks", 1 + getClicks); //Add 1
if (getClicks === 10){ //Check
alert('Locked');
document.getElementById('firstN').disabled= true;
} else {
alert(getClicks); //Remove else statement when you see it works.
}
}
</script>
</head>
<body>
<form action="#">
Input Box: <input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" onclick="check();" clicks="0">
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>