How to display grade as an alert in javascript [closed] - javascript

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 3 years ago.
Improve this question
I have been trying to get this code to work, my assignment is to create a javascript where the user inputs a letter grade then it gives them an alert of what kind of grade they are gonna get. For some odd reason, I cant get the alert working. My teachers example involves using a function but I dont know what to put in there.
<html>
<head>
<script>
Function(){
var x = document.getElementById("score").value;
if x >=1: {
alert("invalid grade")
}
if .99>= x >=.9: {
alert("A");
}
if .89>=x>=.8:{
alert("B");
}
if .79>=x >=.7:{
alert("C");
}
if .69>=x >=.6:Z{
alert("D");
}
if x<=.59:{
alert("F");
}
{
</script>
</head>
<body>
<p>Enter Score in the box:</p>
<input type="text" id="score">
<button onclick=print("x")">click</button
<body>
</html>

See all the comments below:
<html>
<head>
</head>
<body>
<p>Enter Score in the box:</p>
<input type="text" id="score">
<button>click</button>
<!-- Your script should be just before the closing body tag
so that by the time the browser reaches it, all the HTML
will have been read into memory. Your teacher isn't really
showing you the most correct technique if he/she told you
to put it in the HEAD section. -->
<script>
// Set up event handling in JavaScript, not in HTML. Your teacher is wrong
// to teach you that way. First, find the right HTML element, then configure
// it for the event and the function to call when the event occurs.
document.querySelector("button").addEventListener("click", showGrade);
// JavaScript is case-sensitive. Functions use the word "function" (lower case)
// and, in this case, need a name (that you can make up) to be able to call it later.
function showGrade(){
var x = document.getElementById("score").value;
// The condition for an "if" must be in parenthesis
// and when there are multiple parts to the conditon
// you have to use AND (&&) or OR (||) operators and
// each part must be a complete condition on its own.
// Also, the colons you had were incorrect syntax.
// Lastly, because a grade will be only one of your
// choices, you should use "else if" on the second and
// subsequent tests, so that if the first test fails,
// each of the next ones will run. But, once you've
// ruled out all the possiblilites except for one (the
// last one), you don't need to test and just use "else".
// For example, if the grade isn't and A,B,C, or D, it
// must be an F.
if (x >=1 ){
alert("invalid grade")
} else if (x >= .9 && x <= .99) {
alert("A");
} else if (x >= .8 && x <= .89) {
alert("B");
} else if (x >= .7 && x <=.79) {
alert("C");
} else if (x >= .6 && x <= .69) {
alert("D");
} else {
alert("F");
}
}
</script>
</body>
</html>
More reading:
Using .addEventListener() to set up event handlers
Finding elements in the document with .querySelector()
Writing an if...else/if statement

Related

If statements JavaScript, maths will not work in my else statement what am I doing wrong? [closed]

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 3 years ago.
Improve this question
This question is pretty straightforward. I am making a number guessing game and I am now adding an attempts function to my game. Every failed attempt should add 1 to my attempts variable:
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
console.log(numberwang);
console.log(attempts);
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
console.log("Attempts:",attempts)
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
console.log("Attempts:",attempts)
}
}
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
However the else statement argument doesn't work. Each attempt does not add anything to my attempts variable. Can anyone see what is wrong? Thanks in advance.
Note: the else statement is not working for anything mathematical.
You are defining a variable everytime you click.
Removing the "var" from inside the if/else block
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
<script type="text/javascript">
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
console.log(numberwang);
console.log(attempts);
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
}
}
</script>
Your problem is that when you use the var keyword, you are making a new variable. You should remove the var inside both the if and the else. This will let you change the outer attempts variable, and not the new one that you define by using the var.
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
}
console.log("Attempts is: "+attempts);
}
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
I think that I understand what you are having a problem with. You expect what is already logged to the console to change when the variable changes. That's not how console.log works. It only logs the current value of the variable. If you want to see the new value, you should log it again, in this case after each guess is made.

While loop inside if/else

while(playerTwoHealth > 0 && playerOneHealth > 0){
changeScreen("Player1's Turn", "<button id='player1Attack'>Attack</button><button id='player1Defend'>Defend</button>");
$("#player1Attack").click(function(){
var successfulAttack = alert("Did you get this question right?");
if(successfulAttack === true){
playerTwoHealth = playerTwoHealth - 1;
if(playerTwoHealth === 0){
break;
};
}else{
};
});
};
I'm making a educational mathematics game, and In this section of code, I am trying to test the reaction to questions being asked. The function changeScreen changes the title and paragraph sections of the screen to be the specified HTML. On line no. 7-9, the if/else statement is designed to test if a player's health has reached 0, and if it has, break the while loop declared on line 1. However, the break statement throws an illegal break statement error. Please post any suggestions on how to solve.
Move the click event outside of the loop. In fact you don't really need a break since the while loop condition will not be valid when health is 0
while(playerTwoHealth > 0 && playerOneHealth > 0){
changeScreen("Player1's Turn", "<button id='player1Attack'>Attack</button><button id='player1Defend'>Defend</button>");
};
$("#player1Attack").click(function(){
var successfulAttack = alert("Did you get this question right?");
if(successfulAttack === true){
playerTwoHealth = playerTwoHealth - 1;
if(playerTwoHealth === 0){
// Do stuff
};
} else {
};
});
Your break statement is inside a function which you are binding to the click event, so it's not inside the while loop. You should never bind events within a while loop, as this will try to bind the event every time it loops around.
Also, you might want to replace alertwith prompt

trouble with if statement going to button and div

I'm trying to get my function to look at a number entered into a text box, and if it's larger than x number (I put in 5 for example purposes) display one message in theDiv, if less than or equal to, another. Right now I click the button and nothing happens. I'm trying to learn Javascript for the first time, so forgive my ignorance - where did I go wrong? Thank you!!
<script>
function function1()
{
for (var theNumber)
{
var theNumber=parseFloat(document.getElementById('theInput').value);
if (theNumber < 5)
{
document.getElementById('theDiv').innerHTML="Smaller.";
}
else (theNumber >= 5)
{
document.getElementById('theDiv').innerHTML="Larger.";
}
}
</script>
<body>
<input type="button" id="theButton" value="click me!" onclick="function1()"></p>
<div id="theDiv"></div>
</body>
</html>
change this
var theNumber=parseFloat(document.getElementById('theInput').value);
to
var theNumber=parseFloat(document.getElementById('theButton').value);
and dont use any condition in else, else do not take any condition, rather than that you can use else if
First of all, you are missing a closing curly bracket.
And then your else part should not have any conditions.
Your for syntax is wrong and you dont need it here.
Last but not the least, you are getting the value of theInput, that is not there in the form at all.
So your modified code looks like this
function function1() {
var theNumber = parseFloat(document.getElementById('theInput').value);
if (theNumber < 5) {
document.getElementById('theDiv').innerHTML = "Smaller.";
} else {
document.getElementById('theDiv').innerHTML = "Larger.";
}
}
Working example: http://jsfiddle.net/V3QBc/
There are several problems present here.
1.) You do not have a DOM element with an id="theInput"
2.) You are mis-using the for construct, which is for looping. The correct syntax is for (incrementer_variable; condition_to_continue_looping; increment_by) {}
3.) You are specifying an else if condition using only else (meaning your condition will be ignored.
4.) You are missing a closing curly brace (}) to finish defining function1.
To fix these, add a DOM element with id="theInput", remove the for (it's not needed here), add that last curly brace, and either add an if after the else or remove the condition (depending on the behavior you want).
<input type="text" id="theInput">
<input type="button" id="theButton" value="click me!" onclick="function1()">
<div id="theDiv"></div>
and the JavaScript:
function function1() {
var theNumber = parseFloat(document.getElementById('theInput').value, 10);
if (theNumber < 5) {
document.getElementById('theDiv').innerHTML = "Smaller.";
} else if (theNumber >= 5) {
document.getElementById('theDiv').innerHTML = "Larger.";
}
}
Another minor problem (in potentia) is that you are not specifying a radix for parseFloat. This can cause problems if the JavaScript engine thinks your number has a different base than 10. To ensure you always get a base10 number, specify a radix for the second argument to parseFloat: (var x = parseFloat(otherVar, 10);).
Demo: http://jsfiddle.net/8tS7t/

Im having an issue with displaying javascript output without any user action

this is the Question: An integer is said to be prime if it is greater than 1 and divisible only by 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not.
a) Write a function that determines whether a number is prime.
b) Use this function in a script that determines and prints all the prime numbers between 1 and 10000.
How many of these 10000 numbers do you really have to test before being sure that you have found all the primes? Display the results in a <textrarea>.
This is my code:
function isPrime(n)
{
boolean prime=true;
if(n==1 || n==0)
{
prime= false;
}
if(n==2)
{
prime= true;
}
else
{
for(int i=2;i<n;i++)
{
if(n%i==0)
{
prime= false;
}
}
}
return prime;
}
function printPrimes()
{
document.writeln("<textarea rows="10" cols="15">");
for(var i=0; i<=1000; i++)
{
if(isPrime(i)==true)
{
document.writeln("<p>" + i + "</p>");
}
}
document.writeln("</textarea>");
}
printPrimes();
This is My html:
<!DOCTYPE html>
<html>
<head>
<script src="prime.js" type="text/javascript"> </script>
</head>
<body>
<h1> Prime numbers between 1 and 1000 are: </h1>
</body>
When i open the html file on chrome only the header shows up the script doesnt seem to run!
You're importing the script in the <head>, so that's where it's output will go. Try moving it to the <body>.
That's possibly the slowest way to find primes.
edit — another problem is this:
for(int i=2;i<n;i++)
There is no int keyword in JavaScript - it's var. That would cause a syntax error, which would show up in the error console. Neither is there a boolean keyword (declaration of "prime"). It's important to keep the error console open while doing any HTML/JavaScript development.
This is because you are attempting to write the <textarea> to the <head> element. Try loading/executing your script within the <body>.

Javascript random number not displaying result

I've got a webpage which is meant to generate a random number, then when the number =5 it displays a win message..if not display lose message, but its not displaying any alerts..have i missed something out?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function WinLose()
{
var x=document.getElementById("demo");
x=x.innerHTML=Math.floor((Math.random()*5)+1);
return x;
if (x=4)
{
alert("winner!");
}
else
{
alert("loser");
}
}
</script>
</head>
<body>
<p id="demo">Click the button to display a random number between 1 and5.</p>
<button onclick="WinLose()">Try it</button>
</body>
</html>
EDIT:
Managed to get this bit working so now it displays either win or loose depending on its number, yet does anyone know how i can swap the alerts in the if statements to display a DIV section. ive got a jQuery file included so it can accept the hide/show effect...anything i tried didnt work
you have return x after you generate a random value for x. this means no javascript code after that line will run in that function.
also, your if statement needs to use '==' to do the comparison rather than '=' which is assignment.
Yeah, It can be tough. The main problem again has to be other than return x is the "==". So this
if (x=4)
Should really say:
if (x==4)
What you said before was that you were assinging x to 4 so that has no meaning at all and messes everything up.
Hope this helps you!
You need to return x after you generate the random value; and you must add x == 4
function WinLose()
{
var x=document.getElementById("demo");
x=x.innerHTML=Math.floor((Math.random()*5)+1);
if (x==4) {
alert("winner!");
} else {
alert("loser");
}
return x;
}
DEMO
Your code:
x=x.innerHTML=Math.floor((Math.random()*5)+1);
x is receiving x.innerHTML then x.innerHTML = random number.
Correct way: (remove "x=")
x.innerHTML = Math.floor((Math.random()*5)+1);
Here is a simplified version that externalizes the alerts (I assume you don't plan to use them later)
function WinLose(){
var x=Math.floor((Math.random()*5)+1);
document.getElementById("demo").innerHTML=x;
return (x==5) ? "Winner!" : "Loser";
}
alert(WinLose());

Categories