How to display an integer into a div - javascript

I am working on getting the user t input a number for something in this case it would be a resistor value, I have asked them via a prompt to pick a number and then if that number is within the limits I have set then the number would be displayed back to the user within a div.
I have built this already and got it to work with a couple of test messages so I believe the function itself is fine however I am having a problem that whenever the user enters a correct value that value isn't displayed but "undefined" is displayed instead.
This is the HTML I am testing,
<button onclick="R1Value()">Change Value</button>
<div id="test3"></div>
And this is the JavaScript function
function R1Value() {
var R1ValueEntered = prompt("please enter a value for R1:")
var R1 = parseInt(R1ValueEntered)
var display = document.getElementById('test3');
if (R1 >= 120 && R1 <= 1000000) {
display.innerHTML = R1.value;
}
else {
alert("That is an incorrect value please enter one between 120Ohms and 1MOhm.");
}
}
I have placed into into a jsfiddle as even though there isn't a lot of code it may save you some time if you can have a look, http://jsfiddle.net/2ufnK/72/ I may be missing something simple but I can't seem to fix the problem.

Just remove .value :
if (R1 >= 120 && R1 <= 1000000) {
display.innerHTML = R1;
}
FIDDLE

.value is undefined for integers. Remove that and your code will work fine.

You don't need the R1.value. Just calling R1 will return it's value.

you got an error here, you assign R1 value, not R1.value
if (R1 >= 120 && R1 <= 1000000) {
display.innerHTML = R1;
}

I tried your code.
Besides that you might have missed a closing tag, it worked for me. You need to change these lines:
if (R1 >= 120 && R1 <= 1000000) {
display.innerHTML = R1.value;
} else {
alert("That is an incorrect value please enter one between 120Ohms and 1MOhm.");
}
to:
if (R1 >= 120 && R1 <= 1000000) {
display.innerHTML = R1;
} else {
alert("That is an incorrect value please enter one between 120Ohms and 1MOhm.");
}
you don#t need to get the value of R1, because it already IS hte Value.
I hope i could help.
regards

Your problem is that you are never closing your <div> and you also call R1.value, which is basically calling .value on an integer, which is undefined. Try the following:
function R1Value() {
var R1ValueEntered = prompt("please enter a value for R1:")
var R1 = parseInt(R1ValueEntered)
var display = document.getElementById('test3');
if (R1 >= 120 && R1 <= 1000000) {
display.innerHTML = R1;
} else {
alert("That is an incorrect value please enter one between 120Ohms and 1MOhm.");
}
}
<button onclick="R1Value()">Change Value</button>
<div id="test3"></div>

Related

Can't quite get two variables to add and subtract properly. (Javascript)

Currently I'm trying to use prompts to assign an integer to variables, and then add/subtract based on if the input is a negative or positive value, currently it will add, but it won't subtract.
var creditLimit = parseInt(prompt("What is your credit limit?"))
var initialBalance = parseInt(prompt("What is your current balance?"))
var balanceChange = parseInt(prompt("Please enter a charge or a credit amount"))
var newBalance
if (balanceChange > 0) {
newBalance = initialBalance + balanceChange;
} else if (balanceChange < 0) {
newBalance = initialBalance - balanceChange;
} else {
alert("Please enter a valid integer")
}
I know the alert could probably be something better, but right now I'm just breaking down a credit balance calculator and got held up at this spot.
else if (balanceChange < 0) {
newBalance = initialBalance - balanceChange;
}
The balanceChange < 0 i.e it will be a negative value, so initialBalance - (- balanceChange) = initialBalance + balanceChange
that causing the problem here.
Ah, I just figured it out, I suppose I was trying to use a double negative operation by subtracting a negative input!

HTML5 web storage integer becomes NaN

Can anyone explain why last line results in NaN? 'userScore' is an object of a span element and similar operations work perfectly fine when I don't implement the localStorage part. Many thanks in advance!
var score;
score = 20 - (parseInt(turnNr.innerHTML) - bricks.length / 2) *
1.2;
if (score >= 0.5) {
score = Math.round(score);
} else {
score = 0;
}
if (localStorage.totalScore) {
localStorage.totalScore = parseInt(localStorage.totalScore) +
score;
} else {
localStorage.totalScore = score;
}
userScore.innerHTML = localStorage.totalScore;
Your code cannot recover from errors. Once you have stored "NaN" in localStorage, it never will go away when the code is executed. That's because if (localStorage.totalScore) will run even when there's an invalid value.
You'll want to change your code to
if (parseInt(localStorage.totalScore)) { // NaN is falsy and will be ignored
localStorage.totalScore = parseInt(localStorage.totalScore) + score;
} else {
localStorage.totalScore = score;
}
userScore.innerHTML = localStorage.totalScore;

Temperature Converter (IF ELSE conditions) in JavaScript

I am creating a Temperature Converter out of JavaScript. So far only the Celsius conversion works when the user inputs that first. I am just having trouble figuring out how to structure the other if statements.
var conversionC;
var conversionF;
var conversionK;
if ( celsius.value != "" ) {
conversionF = document.getElementById("celsius").value * 9 / 5 + 32;
document.getElementById("fahrenheit").value = Math.round(conversionF);
}
else if ( fahrenheit.value != "" ){
conversionC = (document.getElementById("fahrenheit").value - 32) * 5 / 9;
document.getElementById("celsius").value = Math.round(conversionC);
}
if ( kelvin.value != "" ){
conversionC = document.getElementById("celsius").value - -273;
document.getElementById("kelvin").value = Math.round(conversionC);
}
I only want to keep the one Convert button that I have, and still have it work when the user decides to input a Fahrenheit or Kelvin first.
Any guidance is greatly appreciated!
Here is a JSFiddle of my program so far:
https://jsfiddle.net/2sharkp/kw2sr1wx/
Thanks!
In your JSFiddle, you are taking each value and converting it into a float with parseFloat.
This means that when you hit if ( celsius.value != "" ), you are calling .value on a number, which is undefined. So you're really calling if ( undefined != "" ), which is true, and your first if block will always execute.
I'm assuming that your intention is to take the most recently edited field and use that for the conversion. I would recommend using a flag to indicate which field was last edited.
https://jsfiddle.net/camEdwards/chyg4ws1/
<script>
let cels = document.getElementById('cels');
let fahr = document.getElementById('fahr');
cels.addEventListener('input', function(){
let f = (this.value * 9/5) +32;
if(!Number.isInteger){
return f.toFixed(2);
}
fahr.value = f;
});
fahr.addEventListener('input', function(){
let c = (this.value - 32) * 5/9;
if(!Number.isInteger){
return c.toFixed(2);
}
cels.value = c;
});
</script>

How do i fix this value code

So i want to get this working! Lets say value is within 93-120% of value2, i want the text to change to working or not working!
The issue is i do not know how i am able to do if value is greater than or equal to percentage of value2! I am sure this is an easy fix/line of code.
Thank you.
<html>
<body>
<p id="demo">Display the result here.</p>
<script>
var value = 30;
var value2 = 27;
if (value >= 93% "of lets say value2" && value <= 120% "of same value2") {
document.getElementById("demo").innerHTML = "Working";
} else {
document.getElementById("demo").innerHTML = "Not Working";
}
</script>
</body>
</html>
if (value >= 0.93*value2 && value <= 1.2*value2) {
What about this simple math:
if (value >= 93% "of lets say value2" && value <= 120% "of same value2")
if ( (value/value2) > 0.93 && (value/value2) < 1.2 )
Note:
No need to check for zero of if the values are set (not undefined).
Since if there is any error of this kind it will be NaN or Infinity

JavaScript OnClick Method

I was having trouble with the OnClick method I was learning while creating a game. Every time I enter the value and click the button, it is stuck in a loop, I tried document.write and it works using that, but than it opens a new page instead of showing up on screen.
I am new to the programming community, so any help would be nice.
<body>
<p>Enter an integer between 1-100 here:
<input id="number" type="text" />
</p>
<p>
<button onclick="onclickFunction()" type="button">Enter</button>
</p>
<p id="result"></p>
<script type="text/javascript">
function onclickFunction() {
var a = Math.random();
var b = a * 100;
var c = Math.ceil(b);
var intNumber;
var count = 0;
var bool = false;
do {
do {
intNumber = document.getElementById("number").value;
}
while (intNumber > 100 || intNumber < 0);
if (intNumber > c) {
document.getElementById("result").innerHTML = "Too High " + "</br>";
bool = false
} else if (intNumber < c) {
document.getElementById("result").innerHTML = "Too Low " + "</br>";
bool = false
} else if (intNumber == c) {
document.getElementById("result").innerHTML = "You Win!" + "<br>" + " It took you " + count + " tries";
bool = true
}
count = count + 1
} while (bool !== true);
document.getElementById("result").innerHTML = "Win!";
}
</script>
</body>
Updated:
<script type="text/javascript">
// Declare all your functions first
// These functions expect no parameters and return values.
function onclickFunction()
{
var a = Math.random();
var b = a * 100;
var c = Math.floor(b);
// Input from text box.
var randomNumber = document.getElementById("number").value;
// Output to paragraph.
if (randomNumber < c && randomNumber != c)
{
document.getElementById("result").innerHTML = "Too Low " + "</br>";
}
else if (randomNumber > c && randomNumber != c )
{
document.getElementById("result").innerHTML = "Too High" + "</br>";
}
else if (randomNumber == c)
{
document.getElementById("result").innerHTML = "Win!";
}
// Clear text box for further input.
document.getElementById("name").value = "";
}
</script>
<p>Enter an integer between 1-100 here: <input id="number" type="text" /></p>
<p><button onclick="onclickFunction()" type="button">Enter</button></p>
<p id="result"></p>
</body>
First of all, it is always useful to create a fiddle.
That way people who are reading your question can run your code immediately.
Let's break down the code
var a = Math.random();
var b = a * 100;
var c = Math.ceil(b);
This can be done in a single line, to save variables.
do
{
intNumber = document.getElementById("number").value;
}
while (intNumber > 100 || intNumber < 0);
I'm not a big fan of using do/while loops this way, although it can come handy when you want to run the do code at least once, like now.
This loop keeps running when the number is bigger than 100, or smaller than 0. So if I pick an incorrect number that means my browser crashes.
if (intNumber>c){
document.getElementById("result").innerHTML = "Too High " + "</br>";
bool = false
}else if (intNumber<c){
document.getElementById("result").innerHTML = "Too Low " + "</br>";
bool = false
}else if (intNumber == c){
document.getElementById("result").innerHTML = "You Win!" + "<br>" + " It took you " + count + " tries";
bool = true
}
First you are checking if the guess is bigger than the answer, than if it's smaller. That means that the last check if it's equal is unnecessary, since that is the only option left. You can just use an else here.
Also try to be consistent with your spacing and where you place your curly brackets.
do{
//Stuff
}
and
do
{
//Stuff
}
Are both valid ways to use brackets, but stick to one style or your code will get too confusing.
count = count + 1
A small oversight here is that the count starts at 0. So when you guess the number in a single try, it will say you have done it in 0 tries.
while (bool !== true);
document.getElementById("result").innerHTML = "Win!";
}
All the previous code will be done until bool becomes true. The problem here is that if I entered a wrong number (or an invalid number). The program will keep running the if statement which requires a lot of computer power since it never stops. It is impossible to change your guess and the page crashes, because the browser is stuck in the while loop.
The simplest solution for this is to calculate if the new guess was correct when the player inputs a new number. So when onClickFunction is called again.
That way you never have to use a while loop. Although you have to calculate the random number somewhere else.
I hope that helped, if you have any question let me know!

Categories