Showing an image based on a number range in Javascript - javascript

I am trying to create a javascript program that prompts the user for a number. If a user puts in a number that is less then 21, an image of soda will show. If the number is 21 or greater, the image is beer. There is an image of a bar that is shown when the page loads. Negatives and non-numbers are not allowed in the code. I have worked on this code for over a couple of days and the code does run. The only problem I have with it is that it will say that any input is an invalid entry. I have looked around for any solutions and I'm not sure what to do. I am new to javascript and any help would be appreciated.
Below is the javascript I am using:
function start()
{
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent()
{
let number = document.getElementById('number');
let liquid = document.getElementById('Bar');
if parseInt(number <= 20)
{
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
}
else if (number >= 21)
{
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
else if (isNaN(number) || number < 0)
{
alert("Invalid Entry. Enter a Number.")
}
}
window.onload = start;
Here is the HTML code that goes with it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ID Check?</title>
<script src="scripts/pt2script.js"></script>
</head>
<body>
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" value="Enter a number...">
<button onclick="toggleContent()" id="button1">Submit</button>
</body>
</html>

You need to get the value from input and convert it to a number by using an unary plus +.
function start() {
let button1 = document.getElementById("button1");
button1.onclick = toggleContent;
}
function toggleContent() {
let number = +document.getElementById('number').value; // take value as a number
let liquid = document.getElementById('Bar');
if (isNaN(number) || number < 0) { // move exit condition to top and exit early
alert("Invalid Entry. Enter a Number.")
return;
}
if (number <= 20) { // condition without parseint
liquid.src = 'assets/Soda.png';
liquid.alt = 'Spicy water';
} else { // no need for another check
liquid.src = 'assets/Beer.png';
liquid.alt = 'Angry Juice';
}
}
window.onload = start;
<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" placeholder="Enter a number..."><!-- use placeholder -->
<button onclick="toggleContent()" id="button1">Submit</button>

You are attempting to convert a boolean to an integer. This will not work sense (num >= 20) or whatever will evaluate to true or false, and not a number (NaN). You can convert the value to a number before trying to do a logical comparison. I'd do something such as:
$('.btn').on('click', function() {
let val = $('#num').val();
val = parseInt(val);
if(val >= 21) {
$('img').attr('src', '/path-to-soda');
}
else {
$('img').attr('src', '/other-path');
}
});
As soon as an event triggers your number comparison I would instantly convert it to a number (i'm assuming you are using a number input which will do this for you), and then perform the logical operation. If you're using a number input (which again, i'm just assuming), you won't even need to convert the value to a number. That's only necessary if you're using a text input or something along those lines.

Related

How to call a function containing If/Else using User Input in JavaScript

How do I go about nesting an If/Else statement into a function and then calling that function using a user input in the body in order to make the function calculate the correct alert with JavaScript? I'm missing the knowledge of how to call the statement in the body it seems. Any help would be appreciated! :)
<!doctype html>
<html>
<head>
<title> JavaScript Playground </title>
<script type="text/javascript">
function grade(Grade){
if (Grade <= 90 && Grade >= 100) {
return alert("You made an A!");
} else {
return alert("I don't know what you made!");
}
}
</script>
</head>
<body>
<script>
var Grade = parseFloat(prompt("Please enter a number: "));</script>
</body>
</html>
Several things
Your value cannot be <=90 AND >= 100
No need to return the alert
You need to call the prompt before the grade or move the prompt to the function
Prompt can return empty string, or something not a number so test if it is a number
Your code could be written
function grade(){
var Grade = prompt("Please enter a number: ");
Grade = isNaN(Grade) || Grade.trim()==="" ? 0 : +Grade; // force number if "Not a Number" or an empty string
if (Grade >= 90 && Grade <= 100) {
alert("You made an A!");
} else {
alert("I don't know what you made!");
}
}
grade()
That said,
You should already use eventListeners
It is nicer to use some element's text content than an alert
I also show you a ternary instead of the if (a) text = "a"; else if (b) text = "b" construct
<!doctype html>
<html>
<head>
<title> JavaScript Playground </title>
<script type="text/javascript">
// helper function to make a number from whatever is entered
const makeNum = str => isNaN(str) || str.trim() === "" ? 0 : +str; // convert to 0 if not a number
function grade(Grade) {
Grade = makeNum(Grade); // convert to number
return Grade >= 90 && Grade <= 100 ? "You made an A!" : "I don't know what you made!";
}
window.addEventListener("load",function() { // on page load
document.getElementById("gradeMe").addEventListener("click",function() {
document.getElementById("res").textContent = grade(document.getElementById('grade').value);
})
});
</script>
</head>
<body>
Please enter a number:
<input type="text" id="grade">
<input type="button" id="gradeMe" value="grade me" />
<span id="res"></span>
</body>
</html>
The line directly after
var Grade = parseFloat(prompt("Please enter a number: "));
You can call your function like grade(Grade);
The if/else is completely unrelated to how you call the function but I think the conditional inside your if statement is mixed up. I'm guessing you probably meant for it to be Grade >= 90 && Grade <= 100 rather than Grade <= 90 && Grade >= 100.

JavaScript code does not work as expected

So I made this little thing as I am quite new to programming, but when I open it in Chrome, I am able to type input but then nothing happens. Does anyone know how I can fix this code?
Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<b id="bold">Guess:</b> <input type="text" id="guess">
<input type="submit" value="GO!">
<script>
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low +1)) + low;
return number;
}
var number = getRandomNumber(1,10);
var guess = document.getElementById("guess");
for (var i=0;i=0) {
if (guess>number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too high, try lower!";
}
if (guess<number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too low, try higher!";
}
if (guess==number) {
alert("You're correct, the number is "+number+"!!!");
alert("Thanks for playing my game and have a good day!");
}
}
}
startGame();
</script>
</body>
</html>
You've got a lot of problems, starting with a syntax error.
You have a submit button, but no form to submit. You really just need a button. But, even then, you have to set up a click event handler for it.
Then, your loop isn't configured properly.
You also are not accessing the data the user has typed into the textbox correctly - you need to get the value of the element.
Your if statements should be else if.
The b element should not be used just for presentation. HTML is a "semantic" language, meaning that you use a tag to describe the meaning (not presentation) of an element. For styling use CSS.
See comments inline below for details.
/* CSS is for presentation, not HTML */
#bold { font-weight:bold; }
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<!-- Don't use HTML for styling, use it for semantics. -->
<span id="bold">Guess:</span> <input type="text" id="guess">
<!-- You need a <form> if you have a submit button. For this, you just want a button. -->
<input type="button" value="GO!" id="go">
<script>
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low + 1)) + low;
return number;
}
var number = getRandomNumber(1,10);
var guess = document.getElementById("guess");
// Get a reference to the output area just once
var output = document.getElementById("bold");
// Give the user 3 tries. Your loop wasn't configured properly.
for (var i=0; i < 3; i++) {
// You want to access the data in the textbox. That's the value
// Also, if the first condition isn't true, try the next and so on.
// This is done with else if branches
if (guess.value > number) {
output.textContent = "You're too high, try lower!";
} else if (guess.value < number) {
output.textContent = "You're too low, try higher!";
} else if (guess.value == number) {
alert("You're correct, the number is "+number+"!!!");
alert("Thanks for playing my game and have a good day!");
break; // Get out of the loop because the game is over.
}
}
}
// Set it up so that clicks on the button run the function
document.getElementById("go").addEventListener("click", startGame);
</script>
</body>
</html>
you have some errors:
this doesnt work, it wont loop. actually, why do you want to loop?
for (var i=0;i=0) {
this will run the function once, this means when the user writes the value it wont be checked
startGame();
the button doesnt do anything, also it has a submit and you don't have any forms:
input type="submit" value="GO!">
on each if, the conditions are exclusive, use if/else
below is a working code:
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<b id="bold">Guess:</b> <input type="text" id="guess">
<input value="GO!" onclick="checkGuess()">
<script>
var number = 0;
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low + 1)) + low;
return number;
}
number = getRandomNumber(1, 10);
}
function checkGuess() {
var guess = document.getElementById("guess").value;
if (guess > number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too high, try lower!";
} else if (guess < number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too low, try higher!";
} else if (guess == number) {
alert("You're correct, the number is " + number + "!!!");
alert("Thanks for playing my game and have a good day!");
}
}
startGame();
</script>
</body>
</html>
Although i have no idea about what your program does. you have a syntax error at
for (var i=0;i=0) {
and also you should bind an event to that button rather than doing a submit.

How to take an input that is equal to 10 and perform a function that says awesome to the screen

I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.
<!DOCTYPE html>
<html>
<head>
<title>Fizzbuzz Input Field</title>
<script src="scripts.js"></script>
</head>
<body>
<form>
<input type="number" id="userInput"></input>
<button onclick="fizzBuzz()">Go</button>
</form>
</body>
</html>
window.onload = function() {
alert("Page is loaded");
};
var fizzBuzz = function() {
var userInput = document.getElementById("userInput");
fizzBuzz.onclick = function() {
if(userInput.value == 10) {
document.write("awesome");
};
};
}
Grab the element from the input, in this case, "userInput". grab your button by querying it, or putting an id on it etc... Don't bother with putting a function on the HTML, avoid bad practice. Add an event listener to the button, check to see if it equals 10 and append your text, preferably somewhere suitable.
var input = document.getElementById("userInput");
var button = document.getElementsByTagName('button')[0]
button.addEventListener('click', function(a) {
if (input.value === '10') {
button.after("awesome");
}
})
<input type="number" id="userInput">
<button>Go</button>
I think what you are looking for is eval before using it, you should search the web for why eval is evil.
What you want is something like this:
var button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
// First we get the numeric value written to the input (or NaN if it's not a number)
var inputValue = parseInt(document.getElementById('userInput').value, 10);
// Define the element to which write the text (you usually want a DIV for this)
var outputElement = document.getElementById('outputDiv');
if ( ! isNaN(inputValue) ) {
outputElement.innerHTML = "awesome!";
}
else {
// The value is not a number, so just clean the result
outputElement.innerHTML = "";
}
});
Of course, for this to work, you should have at least:
<input type="number" id="userInput" />
<button id="myButton">Go</button>
<div id="outputDiv"></div>
I don't have any idea how you want the awesome to be displayed. Made it an alert. Have fun.
<script>
function fizzBuzz() {
var fizzBuzz = document.getElementById("userInput").value;
if(fizzBuzz != 10){
alert('Number is not equal to ten!');
}else {
alert('awesome');
}
}
</script>
You are setting a property 'onclick' of function 'fizzBuzz',
you should use the input event.
var userInput = document.getElementById('userInput');
userInput.oninput = function() {
if( this.value == 10 ) alert('awesome');
}

form validation using isNaN()

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div class="basic">
<form id="input">
<p id="content">
<label> Birth Year: <input type="text" id="box1" placeholder="E.g. 1020" ></label> <br></br>
<!-- oninvalid="this.setCustomValidity('Please enter a number.')" -->
<label> Current Year: <input type="text" id="box2" placeholder="E.g. 1220" ></label> <br></br>
<input type="button" value="Calculate" id="submit" onclick="calculateAge(document.getElementById('box1').value, document.getElementById('box2'.value))"/>
</p>
</form>
</div>
<script type="text/javascript">
//previous attempt at form validation and bubble error message.
//error message for form fields
var birth = document.getElementById('box1');
birth.oninvalid = function(event)
{
event.target.setCustomValidity('Please enter a number.');
}
var current = document.getElementById('box2');
current.oninvalid = function(e)
{
e.target.setCustomValidity('Please enter a number.');
}
//function parameters do not have types?
function calculateAge(birthYear, currentYear)
{
var a = birthYear.match("^[0-9]+$").length == 1;
var b = currentYear.match("^[0-9]+$").length == 1;
//var check1 = Number.isInteger(birthYear);
//var check2 = Number.isInteger(currentYear);
var page = document.getElementById("content");
// fire off an error message if one of the two fields is NaN.
if (a ==true && b==true)
{
//var page = document.getElementById("content");
var content = page.innerHTML;
var age = currentYear-birthYear;
var stage;
if (age <18)
{
stage = "Teenager";
}
else if (age >= 18 || age <= 35)
{
stage = "Adult";
}
else
{
stage = "Mature Adult";
}
// \n not working at all...why?
var outputMessage = "Your stage is: " + stage + ".\n" + "Your age is: " + age + "." + '\n';
var node = document.createTextNode(outputMessage);
page.insertBefore(node, page.firstChild);
}
else
{
var outputMessage = "Error: please enter a number.";
var node = document.createTextNode(outputMessage);
page.insertBefore(node, page.firstChild);
}
}
var button = document.getElementById("submit");
button.onclick = function()
{
value1 = button.form.box1.value;
value2 = button.form.box2.value;
calculateAge(value1, value2);
}
</script>
</body>
</html>
I tried "adopting" some of the example code for form validation and my code refused to give me a little bubble that says something along the lines of "wrong input!" like the example code on the documentation had, so i decided to go with a simpler approach.
My goal is to check if the inputs from the form fields are number (no letters/symbols), so im doing an if check to do what i want the form result to do (output the stage/age of the person given their info), else I just want it to fire off a generic error message.
However, the error message does not get fired off even if the "age" output is "NaN". for example filling in box1 with a letter and box 2 with a number, you get stage: (blank) age: NaN. What am I missing?
Edit: implemented suggested change, and changed if check condition.
As you said, you have to validate the input first by checking if it is a number, since you cant calculate strings with numbers obviously.
Take a look at Number.isInteger(value), this is what you need. ;)
Here an overview of its outputs:
Number.isInteger(0); // true
Number.isInteger(1); // true
Number.isInteger(-100000); // true
Number.isInteger(0.1); // false
Number.isInteger(Math.PI); // false
Number.isInteger(Infinity); // false
Number.isInteger(-Infinity); // false
Number.isInteger("10"); // false
Number.isInteger(true); // false
Number.isInteger(false); // false
Number.isInteger([1]); // false
Edit: [Additions]
Also your code is wrong.
// fire off an error message if one of the two fields is NaN.
if (check1 ==true || check2==true)
isNaN(testValue) returns true if testValue is not a number. So what you do in your code is, you check if check1 OR check2 is not a number and if yes, you continue. I dont think thats what you wanted? Because in the else is your error message, and this else will only be called when both are false (means both of them must be not NaN's and this means you write the error exactly then when all is right)
Correct you should ask, when using IsNaN:
if(check1 == false && check2 == false) {
// Everything okay - No error
} else {
// One of them, or both, is not a number - Print error
}

JS Calculation assistance

I'm having some issues with my code, I'm creating a site to get it to calculate mortgages with down payments of:
3% of the first $25,000
Insures home mortgages requiring a down payment as follows:
3% of the first $25,000
5% of the remainder
The input consists of a SSN and a mortgage amount. I wanted it to print the applicant’s SSN and the amount of down payment required. Reject any applications over $70,000. Don’t forget to validate your input. If the input is not good, and I want it to display an error message and ask for the input data again.
<html>
<head>
<title>Mortgage Charges</title>
<script type="text/javascript">
// Program name: FHA
// Purpose: print the applicant’s SSN and the amount of down payment required
// Date last modified: 3/29/12
function mortgage() {
var amtOwed = parseInt(document.frmOne.ssn.value);
var mortgage = 0;
if (mortgage <= 25000) {
amtOwed = 0;
}
else if (mortgage >= 5%) {
}
alert(amtOwed);
document.frmOne.mortage.value = amtOwed;
}
window.onload = function() {
document.frmOne.onsubmit = function(e) {
mortgage();
return false;
};
};
</script>
</head>
<body>
<form name="frmOne">
Enter your SSN:<input type="text" id="ssn" /><br />
Mortgage amount:<input type="text" id="mortage" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I'm afraid I can't fathom your logic. How do you expect this to work?
Let me break down what your current code does:
function mortgage() {
var amtOwed = parseInt(document.frmOne.ssn.value);
// Get the value from the text box, and convert it to a number. That's good.
var mortgage = 0;
// Initialise a variable. Fair enough.
if (mortgage <= 25000) {
// You JUST set morgage=0. How can it be anything but less than 25k?
amtOwed = 0;
// You are overwriting the value you got from the form with 0
}
else if (mortgage >= 5%) {
// Okay, first of all this else will never be reached, see comment above.
// Second... 5% of what, exactly? If you want 5% of a number, multiply the number by 0.05
// Third, what's the point of this block if there's no code in it?
}
alert(amtOwed);
document.frmOne.mortage.value = amtOwed;
}
Basically, your code can be simplified to:
function morgage() {document.frmOne.mortage.value = 0;}
Because that's all it does.
I don't really understand exactly what you're doing, but hopefully explaining what your current attempt is doing will help you to find the answer.

Categories

Resources