trouble with if statement going to button and div - javascript

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/

Related

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

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

JavaScript/jQuery - Multiple Wack-a-Mole Qs: (Increment Score, x/y positioning, click event listener - corrected)

I'm a beginner, obviously, and working on a project for class. I managed to solve 1 step through the site & 1 on my own, but the last 4 are getting more confusing the more I search through these other questions, which I've been doing all day and most of yesterday. I've gone through W3Schools, TutorialsPoint, and tizag.com and still can't figure it out.
Here are the instructions:
Write two functions that generate random whole numbers. One function should return numbers between 0 and 300 (for the y positioning) and the other should return numbers between 0 and 600 (x positioning). Call them (temporarily) from the jQuery ready function and alert() the values.
In the jQuery ready function, write some Javascript/jQuery code which adds a jQuery click event listener to button#start_button. For the time being, add an alert() to test that the button click is working.
Create a function (outside the jQuery ready function) which increments the user's score when called and updates the HTML in span#score. Hint: You should create a global variable to keep track of the score.
Call your score increment function within Document Ready for testing purposes.
This is what I have. Any help would be greatly appreciated. I'm very frustrated.
var mole='<img src="img/mole.jpg"/>'
var score=docutment.getElementById("#score");
$(document).ready(function() {
$("#gamespace").show().html(mole);
$("#timer").show()
document.getElementById("start_button").addEventListener("click", myFunction);
function myFunction(){
alert(Okay);
}; //end alert
}); //end.ready
function getRndInteger(min, max){
var y=Math.floor((Math.random()*300)+1);
function click(){
alert(y);
}; //end alert y
}; //end y
function getRndInteger(min, max){
var x=Math.floor((Math.random()*600)+1);
function click(){
alert(x);
}; //end alert x
}; //end x
function displayScore(){
score.innerHTML=
}; //end score
I guess I should add the rest of the code if anyone whats to test it out.
<div id="content">
<h1>Whack-A-Mole</h1>
<p>After clicking "start", you will have 30 seconds to click
as many moles as you can. The moles appear randomly so be ready! </p>
<div id="controls">
<span id="score">0 pts</span>
<button type="button" id="start_button">Start!</button>
</div>
<div id="timer">30 seconds left</div>
<div id="gamespace">
</div>
</div>
Fixed it!
<script>
var mole='<img src="img/mole.jpg"/>';
var score=0;
$(document).ready(function(){
$("#gamespace").html(mole);
$("#score").click(increment);
$("#timer").show();
$("#start_button").click(function(){
alert("Okay");
}); //end alert
alert(getRndNum());
alert(getRndNumY());
}); //end.ready
function getRndNum(min, max){
var x=Math.floor((Math.random()*600)+1);
return x;
}; //end x
function getRndNumY(min, max){
var y=Math.floor((Math.random()*300)+1);
return y;
}; //end y
function increment(){
$("#score")[0].innerHTML=score;
}; //end increment
</script>
Here are some comments on your code:
Don't forget to end all your lines with semi-colons
var mole='<img src="img/mole.jpg"/>'
Make sure your spelling is correct ('document' is misspelled).
var score=docutment.getElementById("#score");
You're also mixing jQuery and vanilla JavaScript here. To get the element using vanilla JavaScript, you would write the following (note the lack of a # symbol):
var score = document.getElementById('score');
Whereas using jQuery you would write:
var score = $('#score');
'#gamespace' and '#timer' are already visible, so no need to call .show() on them.
$("#gamespace").show().html(mole);
$("#timer").show()
Again, you can use jQuery here:
// JavaScript
document.getElementById("start_button").addEventListener("click", myFunction);
// jQuery
$('#start_button').click(myFunction);
This will look for a variable named Okay. If you want to show the text 'okay', you need to wrap it in quotes.
function myFunction(){
alert(Okay);
}; //end alert
Here, you're defining two functions with the same name, so your second one is overwriting your first.
function getRndInteger(min, max){
// do stuff...
}; //end y
function getRndInteger(min, max){
// do stuff...
}; //end x
You're also not returning any value from the function. You're defining a function called 'click', but you're never calling it or binding it to anything. You're also taking in two parameters (min and max) which you don't use.
function getRndInteger(min, max){
var y=Math.floor((Math.random()*300)+1);
function click(){
alert(y);
}; //end alert y
}; //end y
To write a function that just returns a value from 0 to 300, you would do this:
function randomX(){
var x = Math.floor(Math.random()*300);
return x;
}
You could alert an outcome of randomX by writing
alert(randomX());
I hope that helps you with cleaning up the code you already have, the jQuery documentation is very helpful and will give you an idea of what parameters you need to pass into certain functions, what they do, and what they'll return.

Can I put a variable = another variable in if statements. Or put var = value = another value which it should be equal to?

Hi I'm trying to work on a problem solving webpage that I need for school but so far I'm stuck with the if statement which it will use to calculate.
What I have so far.
<script>
var randomNumberA = Math.round((Math.random() * 50) +1)
var randomNumberB = Math.round((Math.random() * 50) +1)
document.write('He runs at ' + randomNumberA + 'm/s which took him ' + randomNumberB + 's. How far did he run?');
var distance = randomNumberA * randomNumberB
function Submit()
{
var answer = document.getElementById('answer')
if(distance == true){
alert("Congrats! You got it right!");
} else{
alert("Try again!");
location.reload();
}
}
</script>
<body>
<input type='text' id='inputAnswer'/>
<input type='button' onClick='Submit()' value='Submit'/>
</body>
It's not really working and if I put only one "=" then it'll alert as true as long as there's a value in the text box. I plan to make a variable for the textbox value and a variable for the formula and just put If(var1=var2)... so on, but it doesn't work. I'd like to know if it's possible, and if it is how?
If it's not possible can I try to place var1 = formula = textbox id. I'm trying to make it so one variable contains the values that need to be equal so when I declare it in the if statement, I'll just test if it's true or false.
All help is appreciated thanks!
You should compare the calculated distance to the given answer. Now you compare distance to true, which doesn't make sense.
Change it to
if(distance == parseFloat(answer.value)){
You need .value, because answer points to the element. You don't want to compare distance to the element, but to the numeric representation of the element's value.
Also note that you have the id wrong. In html it is inputanswer, while in your script you called it answer.
The version with a single = works, because you assign a value to distance. An assignment can also be used as an expession, which returns the value that was assigned. So if you write if (distance = true), you assign true to the variable distance, and also return true from the expression, resulting in the code inside the if always being executed.
I've made the necessary fixes in the code below, which you can just run from here. As you can see, you were almost there. I just needed to make those two small fixes. :)
var randomNumberA = Math.round((Math.random() * 50) +1)
var randomNumberB = Math.round((Math.random() * 50) +1)
document.write('He runs at ' + randomNumberA + 'm/s which took him ' + randomNumberB + 's. How far did he run?');
var distance = randomNumberA * randomNumberB
function Submit()
{
var answer = document.getElementById('inputAnswer')
if(distance == parseFloat(answer.value)){
alert("Congrats! You got it right!");
} else{
alert("Try again!");
location.reload();
}
}
<body>
<input type='text' id='inputAnswer'/>
<input type='button' onClick='Submit()' value='Submit'/>
</body>
Not completely sure that I understand your question. But, here's some info that will hopefully help:
if(distance == true){
This will render true if there's a value, unless the value is set to false. It's like saying:
if (distance)
If you want to test to see if the value matches the formula, you would just do something like this:
function Submit()
{
var answer = document.getElementById('inputAnswer').value // not 'answer'
if(distance === answer){
alert("Congrats! You got it right!");
} else{
alert("Try again!");
location.reload();
}
}
Hope that helps
you could also get the value via JQuery if your'e using that. It would be the following:
var answer = $('#inputAnswer').val();
Cheers!

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());

Countdown var to loop and display array

I'm very new to javascript and I'm trying to do something I thought would be very basic.
I've created a countdown timer and used "i" as my variable to hold a number from 0-5. And I have an array of "d" from d[0] to d[5] containing strings.
I'm trying to make the timer countdown pass the "i" value into an innerHTML method array value so I want it to display d[5]... d[4]...d[3]... etc.
What am I doing wrong!? Please Help!
<html><head><script language="javascript" type="text/javascript">
var d=new Array():
d[1]="One";
d[2]="Two";
d[3]="Three";
d[4]="Four";
d[5]="Five";
var i=5;
var i=setInterval("timer()",2000); //1000 will run it every 1 second
function timer() {
i--;
if (i <= 0)
clearInterval(countD);
return;
}
}
document.getElementById(timer).innerHTML = d[i];
</script>
</head>
<body>
<h1>
<p id="timer"></p>
</h1>
</body>
</html>
Also, document.getElementById(timer).innerHTML = d[i];
should be document.getElementById("timer").innerHTML = d[i];
id names need to have quotes around them because they are not names of variables. The variable 'timer' is undefined.
Also, you are missing a curly brace on the line if (i <= 0). I am assuming that you meant to exit the function if this if statement is true.
Also, you have a colon instead of a semicolon on the line var d=new Array():
Also, you can't have a paragraph tag inside of an h1
Also, you should encapsulate all of this javascript into a function called something like init. I believe that the javascript code in the head runs before the html is loaded. The javascript can't therefore find the tag. Then, use <body onload="init()"> as your body tag.
EDIT: As the commenters have stated, you are using the variable i for multiple unrelated things.
I'm sorry to say but your code is quite a mess; here's one way to get your code to work, along with a working example:
<html>
<head>
<script language="javascript" type="text/javascript">
var d=new Array();
d[0]="One";
d[1]="Two";
d[2]="Three";
d[3]="Four";
d[4]="Five";
var i=4;
var myTimer =setInterval(timer,2000); //1000 will run it every 1 second
function timer() {
document.getElementById("timer").innerHTML = d[i];
i--;
if (i < 0){
clearInterval(myTimer);
}
}
</script>
</head>
<body>
<h1>
<p id="timer"></p>
</h1>
</body>
</html>
The problems with your JavaScript
You've got two declarations for i, one after the other - one is set to 5 and the other to the setInterval timer
What is countD in clearInterval(countD);?
document.getElementById(timer).innerHTML = d[i]; is attempting to use the function timer as the argument to getElementById. It should be in quotes: document.getElementById("timer").innerHTML = d[i];
It is also being invoked only once since it's not inside the function that is being called by the timer.
var d=new Array(): should be terminated by a ;(semi-colon) and not a : (colon)
You have unmatched braces - your if statement doesn't have an opening brace ({) but it does have a closing one.
Note that while setInterval("timer()", 1000) is valid JavaScript, it depends on eval which should be avoided if possible. The alternate, preferred way to use this is setInterval(timer, 1000) i.e. passing the function and not a string.

Categories