in this excercise i create a counter that has a number display and 2 button to lower and increase number. i assign number to parseInt(num) to convert num object to number. i use alert to check type of number. typeof(number) return number but number return NaN. please someone explain.[edit]reading comment, i was able to solve the problem. i have upadated the solution
var low = document.getElementById("low")
var add = document.getElementById("add")
low.addEventListener("click", function () {
var num = document.getElementById("num")
var number = parseInt(num.innerText)
num.innerHTML = number - 1
})
add.addEventListener("click", function () {
var num = document.getElementById("num")
var number = parseInt(num.innerText)
num.innerHTML = number + 1
})
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- <link rel="stylesheet" href="style.css"> -->
</head>
<body>
<div class="container">
<h1>counter</h1>
<h1 id="num">0</h1>
<div class="btn">
<button id="low">lower count</button>
<button id="add">add count</button>
</div>
</div>
<script src="js.js"></script>
</body>
</html>
You are trying to parseInt(num) but num is DOM element - not number. You want its content. You can get it with .innerText.
const num = document.getElementById("num")
console.log(num);
console.log(parseInt(num));
console.log(parseInt(num.innerText));
<h1 id="num">0</h1>
Related
I have two buttons when clicked I want to call functions I wrapped all my function in play() function
I tried to an addEventListener to the guess button but it only runs the alert only twice after the window is refreshed.
function play() {
let numInput = document.getElementById("input-number");
let resultText = document.getElementById("result-text");
let btnReset = document.getElementById("btn-reset");
let btnGuess = document.getElementById("btn-guess");
let numRandom = null;
function getRandomNumber(min, max){
return Math.floor(Math.random() * (max - min + 1) + min);
}
function guessTheNumber(){
numRandom = getRandomNumber(1,5);
numInput = numInput.value;
alert("button clicked")
}
btnGuess.addEventListener("click",function (){
guessTheNumber();
});
}
play();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Guess That Number</title>
<link rel="stylesheet" href="guessthatnumber.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght#0,100;0,300;0,400;1,100&display=swap" rel="stylesheet">
</head>
<body>
<main>
<h3 class="game-header">Guess the number!</h3>
<p class="game-instruction">Enter a number between 1 - 5 below:</p>
<input class="game-input" type="text" id="input-number"
placeholder="Enter your number here"
tabindex="1" autofocus >
<h4 class="game-result" id="result-text">Success!</h4>
<div class="btn-container">
<button class="btn-clear" id="btn-reset">Reset</button>
<button class="btn-guess" id="btn-guess">Guess</button>
</div>
</main>
<script src="guessthatnumber.js"></script>
</body>
</html>
It is happening because you are changing numInput value every time button is pressed..
numInput = numInput.value;
first iteration:
numInput is equal to value inside an input (lets say it is 5)
so the numInput is 5
second iteration:
numInput is equal to numInput.value and since 5 does not have .value attribute, it is undefined and you get error
The issue with the code is in guessTheNumber function.
You are calculating the random number using numRandom = getRandomNumber(1, 5); and in the next line you are assigning numInput = numInput.value;. Here numInput is your input element. You are overwriting that variable with a number. Next time when guessTheNumber executes numInput will be a string and numInput.value will be undefined. Third time you are trying to access value of undefined, this will throws a console error like Uncaught TypeError: Cannot read properties of undefined (reading 'value')
Correct that code segment to make your code stable.
I have commented that section to make the code not broken.
function play() {
let numInput = document.getElementById("input-number");
let resultText = document.getElementById("result-text");
let btnReset = document.getElementById("btn-reset");
let btnGuess = document.getElementById("btn-guess");
let numRandom = null;
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function guessTheNumber() {
numRandom = getRandomNumber(1, 5);
// numInput = numInput.value;
console.log(numRandom);
alert("button clicked")
}
btnGuess.addEventListener("click", function () {
guessTheNumber();
});
}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght#0,100;0,300;0,400;1,100&display=swap"
rel="stylesheet">
<main>
<h3 class="game-header">Guess the number!</h3>
<p class="game-instruction">Enter a number between 1 - 5 below:</p>
<input class="game-input" type="text" id="input-number" placeholder="Enter your number here" tabindex="1" autofocus>
<h4 class="game-result" id="result-text">Success!</h4>
<div class="btn-container">
<button class="btn-clear" id="btn-reset">Reset</button>
<button class="btn-guess" id="btn-guess">Guess</button>
</div>
</main>
Several things
Calling the variable numInput the same as the field is not a good idea and is the main issue in your code
You did not toggle the success
You can simplify the code by moving the functions outside
const numInput = document.getElementById("input-number"),
resultText = document.getElementById("result-text"),
btnReset = document.getElementById("btn-reset"),
btnGuess = document.getElementById("btn-guess");
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function play() {
let numRandom = getRandomNumber(1, 5);
let num = +numInput.value;
resultText.hidden = numRandom != num;
console.log(numRandom === num ? "you guessed right" : "you guessed wrong")
}
btnGuess.addEventListener("click", play)
btnReset.addEventListener("click", function() { resultText.hidden = true; numInput.value = ""; })
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Guess That Number</title>
<link rel="stylesheet" href="guessthatnumber.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght#0,100;0,300;0,400;1,100&display=swap" rel="stylesheet">
</head>
<body>
<main>
<h3 class="game-header">Guess the number!</h3>
<p class="game-instruction">Enter a number between 1 - 5 below:</p>
<input class="game-input" type="text" id="input-number" placeholder="Enter your number here" tabindex="1" autofocus>
<h4 class="game-result" hidden id="result-text">Success!</h4>
<div class="btn-container">
<button class="btn-clear" id="btn-reset">Reset</button>
<button class="btn-guess" id="btn-guess">Guess</button>
</div>
</main>
<script src="guessthatnumber.js"></script>
</body>
</html>
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 1 year ago.
Improve this question
I'm looking for a solution to calculate 15% of the amount of goods. Currently i have this code:
function getDomNodesBySelector(selector) {
return Array.from(document.querySelectorAll(selector));
}
document.querySelector('.total__button').addEventListener('click', applyDiscount);
function applyDiscount() {
let numPrice = getDomNodesBySelector.forEach(function (item) {
let numDiscount = 15;
let totalValue = numPrice - (numDiscount / 100);
return totalValue;
})
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Order Cart</title>
<link rel="stylesheet" href="https://code.s3.yandex.net/web-code/entrance-test/lesson-2/task-2/fonts.css">
<link rel="stylesheet" href="style.css">
</head>
<div class="card__price">
<p class="card__rub price-default"><span class="price-value">6390</span></p>
</div>
</article>
<section class="total page__total">
<button class="total__button">Use discount 15%</button>
<div class="total__prices">
<h2 class="total__title">Total:</h2>
<p class="total__rub price-default"><span class="total-price-value">46910</span></p>
</div>
</section>
<script src="./task.js"></script>
</body>
What am i doing wrong? And how to fix the issue?
Thanks in advance.
The argument to the event listener is the event, not a list of DOM elements to loop over. You need to call getDomNodesBySelector() to get the list of elements, and specify the selector for the prices that you want to apply the discounts to. I've guessed a class name, replace that with the appropriate selector for your cost elements.
Then you need to accumulate all the discounted prices. I've used the reduce() method below to do this. Since the card prices are in <span> rather than <input>, you need to use .innerText to get the price, not .value.
To get the discounted price, you need to subtract the discount fraction from 1.
The return value of an event listener isn't shown anywhere, so it needs to update the DOM to display the total.
function getDomNodesBySelector(selector) {
return Array.from(document.querySelectorAll(selector));
}
document.querySelector('.total__button').addEventListener('click', applyDiscount);
function applyDiscount() {
let items = getDomNodesBySelector(".price-value");
let numDiscount = 15;
let totalValue = items.reduce((acc, cur) => acc + (1 - (numDiscount / 100)) * cur.innerText, 0);
document.querySelector(".total-price-value").innerText = totalValue;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Order Cart</title>
<link rel="stylesheet" href="https://code.s3.yandex.net/web-code/entrance-test/lesson-2/task-2/fonts.css">
<link rel="stylesheet" href="style.css">
</head>
<div class="card__price">
<p class="card__rub price-default"><span class="price-value">6390</span></p>
</div>
</article>
<section class="total page__total">
<button class="total__button">Use discount 15%</button>
<div class="total__prices">
<h2 class="total__title">Total:</h2>
<p class="total__rub price-default"><span class="total-price-value">46910</span></p>
</div>
</section>
<script src="./task.js"></script>
</body>
When i use the function to check if number is positive or negative it works fine but when i try to do it again nothing happens i have to refresh the whole page to make it work again. Any help is welcome!
const userNum = document.querySelector(".user-input").value;
const checkBtn = document.querySelector(".check-input");
const result = document.querySelector(".result");
function checkNum() {
if (userNum > 0) {
result.innerHTML = "Positive!!"
}
else if (userNum < 0) {
result.innerHTML = "Negativeee!!"
}
else if (userNum < 0) {
result.innerHTML = "Number is NULL"
}
else {
result.innerHTML = "Enter a Number!!"
}
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="intro">
<h1>A Program to Check if number is <br></h1>
<h2>Positive, Negative or Null</h2>
</div>
<div class="check-number-type">
<input type="text" class="user-input">
<button onclick="checkNum()" class="check-input">Check</button>
</div>
<div class="show-result">
<p class="result"></p>
</div>
</div>
</body>
<script src="/script.js"></script>
</html>
The reason why you say you have to "reload" the page everytime is because your code that extracts the input value was placed outside of your checkNum function that determines if it's positive or negative.
You only retrieve the input once, when the script starts, instead of getting a fresh copy everytime you enter the checkNum function.
Just move this:
const userNum = document.querySelector(".user-input").value;
Inside the checkNum() function.
I'm trying to create a code that can increase and decrease via clcik of a button
html code but the problem is i cant get it to function I've tried different options.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<div id="body">
<h1>COUNTER</h1>
<span id="time">0</span><br>
<button id="lower" onclick="reduceone()" type="button">LOWER COUNT</button><BR>
<button id="add" onclick="addone()" type="button">ADD COUNT</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="index.js"></script>
</body>
</html>
javascript code:
$("#add").click(function (){
let count = 0;
count ++;
$("#time").text(count);
});
$(#lower).click(function(){
let count = 0;
count --;
$("#time").text(count)
});
Try this
let count = 0;
$("#add").click(function (){
count ++;
$("#time").text(count);
});
$(#lower).click(function(){
count --;
$("#time").text(count)
});
You have to make variable (count ) a global variable so all functions can access his value . If you put variable(count) in a function then only that function can access his value . Hope you understand
You need to share the state between two functions so each of them could see the shared state that they are changing.
Also, all id or class names should be between inverted commas like that "#lower"
let count = 0; // Shared state that both functions can see
$("#add").click(function (){
count++;
$("#time").text(count);
});
$("#lower").click(function(){ // "#lower" not #lower
count--;
$("#time").text(count)
});
I am making a clicker game. When I display the moneyCurrent variable I get incorrect numbers. The numbers don't actually join. This is in the sellTech() function.
If you want the full project go to enter link description here techClicker
This is on repl.it and that is not the problem.
I have tried parseInt() and Number() and the numbers keep adding like
they are strings.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Tech Clicker</title>
<link rel="shortcut icon" type="image/png" href="IMAGE"/>
<link href="techClicker.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Tech Clicker</h1>
<h2 id="moneyValueText">$0</h2>
<div id="ccDiv">
<input id="ccMakeButton"type="image" src="IMAGE"
onclick="ccClickFunc()" width="50"
height="50">
<p> </p>
<button id="ccSellButton"onclick="sellTech()">Sell Computer
Chips</button>
<h4 id="ccCounter">Computer Chips = </h4>
</div>
<div id="usbDiv">
<input id="mcMakeButton"type="image"
src="IMAGE"
onclick="mcClickFunc()" width="38"
height="26">
<p> </p>
<button id="mcSellButton"onclick="sellTech()">Sell Memory Chips</button>
<h4 id="mcCounter">Memory Chips = </h4>
</div>
<script src="clickGainFunc.js"></script>
<script src="sellTechV2.js"></script>
</body>
</html>
var ccPrice = 0.25
var ccSellAmount
var mcPrice = 0.35;
var mcSellAmount;
//JAVASCRIPT
function sellTech(){
ccSellAmount = cc * ccPrice;
mcSellAmount = mc * mcPrice;
moneyCurrent = ccSellAmount + mcSellAmount;
document.getElementById("moneyValueText").innerHTML = moneyCurrent;
cc = 0;
mc = 0;
document.getElementById("ccCounter").innerHTML = "Computer Chips = " + cc;
document.getElementById("mcCounter").innerHTML = "Memory Chips = " + mc;
}
I expected that the numbers would add up and not drop in value.
This is a little hard to explain so go to
https://techclicker--beraemirkoklu.repl.co/
and then click on the computer chip once. And then sell it. 0.25. If you sell 2, 0.5. if you sell 1, again .25. I am trying to fix that too.