if and else statement condition values not being recognized - javascript

I am trying to create a block of code that takes a users input value and compares it to a random number generated when the page loads. Right now the if statement in the guess function is displaying regardless of what the value of the conditions are. If they are true it displays the first and third message and if it is wrong it also displays those two. What changes should I make to my code in order to get the if statement to alert the correct response in correlation with the users input value.
<html>
<head>
<script>
window.addEventListener("DOMContentLoaded", setup);
void setup(); {
var rNumber1 = Math.random(1-100);
var rNumber = Math.floor(rNumber1);
}
</script>
</head>
<body>
<form>
<table>
<tr><td><label>Enter Guess:</label></td><td><input id="guessedNumber" type="text" /></td></tr>
<tr><td><label>Is Correct?: </label></td><td><label id="guessResult"></label></td></tr>
<tr><td> </td><td><button type="button" onclick="guess()">Submit Guess</button></td></tr>
</table>
</form>
<script>
function guess() {
var guessedNumber = document.getElementById("guessedNumber");
if (guessedNumber != rNumber) {
alert("Your guess is incorrect. Try Again!");
} else if (guessedNumber == NaN) {
alert("Please enter a valid Number");
} else (guessedNumber == rNumber)
alert("You guessed correctly!");
}
</script>
</body>
</html>

Try:
var guessedNumber = document.getElementById("guessedNumber").value;
Also, the Math.random() method always returns a value between 0 and 1 excluding 1. It takes no parameters. Moreover, the way you have passed it parameters using the - sign will subtract the former number from the latter. The way it is used to generate a random number from 1-100 is usually:
rNumber1 = (Math.random()*100+1)
It will multiply the number times 100 and adds 1 to it which ensures that you never get 0. Also, you won't get 101 because it returns a value between 0 and 1 excluding 1.

get the value of from the input box using .value
also, i did not see any open parenthesis in the else statement, and removed the condition in else statement.
setup() is not defined anywhere so i dont know what you are trying to do with that
<html>
<head>
<script>
//window.addEventListener("DOMContentLoaded", setup);
//void setup(); {
//var rNumber1 = Math.random(1-100);
var rNumber = Math.floor(Math.random() * 100) + 1
//}
</script>
</head>
<body>
<form>
<table>
<tr><td><label>Enter Guess:</label></td><td><input id="guessedNumber" type="text" /></td></tr>
<tr><td><label>Is Correct?: </label></td><td><label id="guessResult"></label></td></tr>
<tr><td> </td><td><button type="button" onclick="guess()">Submit Guess</button></td></tr>
</table>
</form>
<script>
function guess() {
console.log(rNumber);
var guessedNumber = parseInt(document.getElementById("guessedNumber").value);
if (guessedNumber != rNumber) {
alert("Your guess is incorrect. Try Again!");
} else if (guessedNumber == NaN) {
alert("Please enter a valid Number");
} else {
alert("You guessed correctly!");
}
}
</script>
</body>
</html>

Related

How to check if textbox value is not number?

<!DOCTYPE html>
<html>
<body>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
<script>
$(document).ready(function () {
jQuery("#text").on("change", function () {
var x = $('#text').value;
if (isNaN(x))
{
window.alert("You have entered not a number");
return false;
});
});
});
</script>
</body>
</html>
I am trying to write javascript code to check if the given value is not number.If not i would like to give error message? If it is number I would like to check if it is integer and between 0 and 100.
Basically you need to convert to an Int before compare it with NaN which means something like:
var x = $('#text').value;
if ( isNaN( parseInt(x) ) ) {
// Not a decimal number.
}
There are a lot of syntax errors in your code.
Your selector checks your div for the change event instead of your input, which means it will never trigger the code.
You should use .val() to get the value of an element when using jQuery selectors instead of .value.
You can also use the this keyword inside the event handler to get the referenced element.
Besides that there were some misplaced ) and } in your code.
Below I have included an working sample of your code.
$(document).ready(function() {
jQuery("#text > input").on("change", function() {
var x = $(this).val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
} else if (x > 0 && x < 100) {
alert("number in between 0 and 100");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
function numberOrNot(var input)
{
try
{
Integer.parseInt(input);
}
catch(NumberFormatException ex)
{
return false;
}
return true;
}
this will return true if your input is number, otherwise it will return false
try this code
you enter direct input on change or write id for input and pass it to javascript
$(document).ready(function() {
jQuery("input").on("change", function() {
var x = $('#text').val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
}
else{
if(x>=0 && x<=100)
{
window.alert("You have enter write number");
}else{
window.alert("You enter number between 0 to 100");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="CommentBox">
Some text :
<input type="text" id="text" />
</div>
You can use try-catch and put as many conditions you want in try block Like this. I have put three conditions for now.
<script type="text/javascript">
function Validation(){
var number1=document.LoginForm.number1.value;
try{
if(number1==""){
throw "Empty";
}
if(isNaN(number1)){
throw "Not a Number";
}
if(number1<0 || number1>100){
throw "Out of range";
}
}
catch(err){
if (err=="Empty"){
alert("Number 1 and Number 2 fields cannot be empty");
}
if (err=="Not a Number"){
alert("Please enter a number");
}
if(err=="Out of Range"){
alert("Out of Range");
}
return false;
}
//return true;
}
</script>

inner.html / handlers

as an incoming javascript coder, i'm stuck at a sample exercise...
<script language="JavaScript">
var num1;
var messages;
var answer = document.getElementById("guess").value;
var counter = 0;
answer = Math.floor(1 + Math.random() * 32);
function start() {
var button = document.getElementById("guessButton");
button.addEventListener("click", Myguess, false);
};
function Myguess() {
num1 = document.getElementById("guess").value;
do {
if (num1 == answer) {
messages.innerHTML = "Ahah!"
}
if (num1 < answer) {
messages.innerHTML = "Either you know the secer or you got lucky!";
}
if (num1 > answer) {
messages.innerHTML = "you should be able to do better";
}
}
}
</script>
<body>
<form action="#">
<input id="guessButton" type="button" value="guess">
<input id="inputfield" type="number" value="guess a number 1- 32">
</form>
</body>
this is supposed to print:
number of guesses is 5 or fewer: "either you know the secret or you got lucky"
Or number of guesses is 5 or more:"you should be able to do better"
Or number of guesses in 5 tries : "ahah!"
however it's not printing .../././
Initially there are few syntax errors to correct
do {} without while is not valid javascript.
start() is never called. I'm guessing you intended to use window.onload = start or <body onload="start();">
Your script is executed before the HTML elements it is modifying. If you want to access elements from the DOM you should access them within a function and/or place the script at the bottom of the body tag.
<script language="JavaScript"> is deprecated. I think you mean <script type="text/javascript"> although as that is the default the type is optional.
The messages variable is never assigned
You set text as the value to a number input. I suspect you intended to use placeholder="guess a number 1- 32". Note that placeholder is actually used to provide a hint about expected input. Direct instructions should use a label. This doesn't affect your javascript but is worth considering all the same.
Additionally myGuess() currently checks if the submitted value is less than the answer or more. You need to increment a count value and compare against that.
The below example do what you need
<form action="#">
<label for="inputfield">guess a number 1-32</label>
<input id="guessButton" type="button" value="guess">
<input id="inputfield" type="number">
</form>
<p id="messages"></p>
<script type="text/javascript">
var num1;
var target = 5;
var messages = document.getElementById("messages");
var counter = 0;
var answer = Math.floor(1 + Math.random() * 32);
function start() {
var button = document.getElementById("guessButton");
button.addEventListener("click", Myguess, false);
};
function Myguess() {
num1 = document.getElementById("inputfield").value;
if(num1 == answer) {
if (counter === target) {
messages.innerHTML = "Ahah!"
}
if (counter < target) {
messages.innerHTML = "Either you know the secer or you got lucky!";
}
if (counter > target) {
messages.innerHTML = "you should be able to do better";
}
} else {
counter++;
messages.innerHTML = "Keep trying";
}
}
window.onload = start;
</script>
<script language="JavaScript">
var num1;
var messages; // should be initialized inside start because at this moment it doen't exist
var answer;
var counter = 0;
answer = Math.floor(1 + Math.random() * 32);
window.addEventListener("load", start); // on loading the page call start;
function start() {
messages = document.getElementById("message"); // this should be something
var button = document.getElementById("guessButton");
button.addEventListener("click", Myguess, false);
};
function Myguess() {
num1 = document.getElementById("inputfield").value; // the id is "inputfield" not "guess"
if (num1 == answer) {
messages.innerHTML = "Ahah!"
}
// else if to stop checking again (if is correct but not the best)
else if (num1 < answer) {
messages.textContent = "Either you know the secer or you got lucky!"; //textContent is better than innerHTML
}
// same here
else if (num1 > answer) {
messages.innerHTML = "you should be able to do better";
}
}
</script>
<body>
<form action="#">
<input id="guessButton" type="button" value="guess">
<input id="inputfield" type="number" value="guess a number 1- 32">
</form>
<div id="message"></div>
</body>
Note: you was using do-while incorrectly (you was messing the while part). Anyway, do-while or any other loop will just loop forever if the answer is not correct because you are not letting the user to re-enter a number. What you need is to check whether the number is correct or not whenevr the user click the button (that parts you had it correct because you used the event listener).
What your code was doing (or supposed to be doing) is check if a user clicks the button and then loop if his answer was incorrect untill the answer is is correct (which is not going to happen because you never give the user another chance to enter a number again. He will get a chance after the function execution is finished. And because of the loop it will never be finished). It was never going to work because the loop waits for the user to enter another number (a correct one) to exit and the user is waiting for the loop to end to enter another number (see the paradox).
What it should do is to wait for the user to enter a number, check that number, prints the message accordingly for that number and then give the user to enter another number. (It is a loop (cycle) already so why need another loop)
The code you need is this:
<body>
<form id="form">
<input id="guessButton" type="submit" value="guess">
<input id="inputfield" type="number" placeholder="guess a number 1-32">
</form>
<div id="messages"></div>
<span id="counter"></span> tries
</body>
<script language="JavaScript">
document.getElementById('form').onsubmit = function() {
return Myguess();
};
var num1;
var messages = document.getElementById("messages");
var counterDiv = document.getElementById("counter");
counterDiv.innerHTML = 0;
var counter = 0;
answer = Math.floor(1 + Math.random() * 32);
function Myguess() {
num1 = document.getElementById("inputfield").value;
if (num1 == answer) {
messages.innerHTML = "Ahah!"
}
if (num1 < answer) {
messages.innerHTML = "Either you know the secer or you got lucky!";
}
if (num1 > answer) {
messages.innerHTML = "you should be able to do better";
}
counter++;
counterDiv.innerHTML = counter;
return false;
}
</script>
You can test it in this JSFiddle.
The function Myguess() is called when the form is submitted. There was no div messages missing in your code, so I added it. I also added the counter span which shows how many tries the player has had. Also the message "guess a number 1-32" is better added as placeholder. I hope that was helpful !

If else statement trouble javascript

My goal here is to check x and see if it is less than or equal to 100, & if it is more than or equal to 0. IF true: alert("entered grade is valid") if false: alert("entered grade is not valid").
I do not understand what i'm doing wrong, it just keeps returning any number ( for example 50, which meets both requirements) inputted as false.
my code:
<!DOCTYPE html>
<html lang="en-US">
<title> Bitar_Grade Calculator </title>
<head>
<script>
var x = document.orderForm.stuentgrade.value;
function checkGrade()
{
if (x>=0 && x<=100)
{
alert("Entered grade is valid!");
}
else
{
alert("Entered grade is invalid!");
}
}
</script>
</head>
<body>
<form>
Please enter the students grade:<br>
<input type="number" name="studentgrade"><br>
</form>
<button onclick="checkGrade()"> Enter</button>
</body>
</html>
You have some typo and errors in your code
See working function
function checkGrade() {
var x = document.getElementsByName('studentgrade')[0].value
if (x>=0 && x<=100) {
alert("Entered grade is valid!");
}
else {
alert("Entered grade is invalid!");
}
}
Try to move the reading of the form field inside the function that does the checking (and add a bit more checking for valid values), like this;
function checkGrade()
{
var x = parseInt(document.orderForm.studentgrade.value);
if (x && x>=0 && x<=100)
{
alert("Entered grade is valid!");
}
else
{
alert("Entered grade is invalid!");
}
}
However, note that this is not a full solution to validating intereg values, so somebody entering "3million" will still be validated as "3"
x is out of scope, you have no form name "orderForm", and theres a spelling mistake in your object name, stuentform...
Give your input an id, and do something like:
function checkGrade()
{
var x = document.getElementById('studentgrade').value;
if ( x>=0 && x<=100 )
{
alert("Entered grade is valid!");
}
else
{
alert("Entered grade is invalid!");
}
}

Number Guessing Game using while loop

In this project, I need to set a maximum of 10 guesses, an indication of what number is being guessed and keep those results on the screen at the end of each game without overwrite the previous guesses.
Each set of guess output needs to be numbered to indicate how many guesses have been made. For the output, I need to use innerHTML. The user will guess a number from 1 to 999. I have to use while loop.
So far this is the code where I'm working and I have some errors and it's not working. Can anybody put me in the right direction to finish this code?
The errors that I found when I inspect the document are checkGuess() function and an anonymous function with a message "Cannot read property 'value' of null"
<script type="text/javascript">
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.getElementById("guesses");
var lastResult = document.getElementById("lastResult");
var lowOrHi = document.getElementById("lowOrHi");
var guessSubmit = document.getElementById("guessSubmit");
var guessField = document.getElementById("guessField");
var guessCount = 1;
function checkGuess() {
var userGuess = Number(guessField.value);
guesses.innerHTML += userGuess + "";
}
while (guessCount == 10) {
lastResult.innerHTML = "!!!GAME OVER!!!";
disableForm();
} else {
if (userGuess == randomNumber) {
lastResult.innerHTML = "Congratulations! You got it right!";
lowOrHi.innerHTML = "";
disableForm();
} else {
lastResult.innerHTML = "Wrong!";
if (userGuess < randomNumber) {
lowOrHi.innerHTML = "Your guess is too low!";
} else if (userGuess > randomNumber) {
lowOrHi.innerHTML = "Your guess is too high!";
}
}
guessCount++;
guessField.value = "";
}
}
function disableForm() {
var wholeForm = document.querySelector(".form"); // grab a reference to the whole form (the contents of the div with class form)
wholeForm.style.opacity = 0.5; // change the opacity of the form to 0.5
guessField.setAttribute("disabled", "disabled");
guessSubmit.setAttribute("disabled", "disabled"); // disable the form field and submit button so they can no longer be used
}
guessSubmit.onclick = checkGuess;
</script>
</head>
<body>
<h1>Number guessing game</h1>
<p id="guesses"></p>
<p id="lastResult"></p>
<p id="lowOrHi"></p>
<div class="form">
<label for="guessField">Enter your next guess: </label>
<input type="text" id="guessField">
<button id="guessSubmit">Enter Guess</button>
</div>
<p></p>
</body>
</html>
Your program is all wrong and is actually doing nothing
the only thing that actually executes is everything outside your functions,
and those are being called only when the page is loaded for first time
in order to execute your CheckGuess you need to actually call it :
<button id="guessSubmit" onclick="checkGuess() ">Enter Guess</button>
but everything else that is actually outside of your functions are only executed when the page is loading
also you have a while--else statement, that's not even possible
then again... it is outside a function so it is useless
You need to put everything on one single statement
YOU DO NOT NEED A WHILE
once you write something down on the page it will stay there until it reloads
if you write a while like that you will just loop your code endless.
this code and logic is so wrong in so many ways i will sent you a functional code :
<script type="text/javascript">
var guesscount =0;
var randomNumber = Math.floor(Math.random() * 100) + 1;
function checkGuess()
{
guesscount = guesscount +1;
var userGuess = document.getElementById("guessField").value;
document.getElementById('guesses').innerHTML += Number(userGuess)+ '<br>';
CheckResults();
}
function CheckResults()
{
//add here your logics if the number is wrong
if ( guesscount>= 10)
{
document.getElementById("guessField").disabled = true;
document.getElementById("guessSubmit").setAttribute('disabled', 'disabled');
document.getElementById('guesses').innerHTML += 'game Over !';
}
}
</script>
</head>
<body>
<h1>Number guessing game</h1>
<label id="guesses"></label>
<label id="lastResult"></label>
<label id="lowOrHi"></label>
<div class="form">
<label for="guessField">Enter your next guess: </label>
<input type="text" id="guessField">
<button id="guessSubmit" onclick="checkGuess() ">Enter Guess</button>
</div>
<p></p>
</body>
</html>

Getting the value of prompt box into another function

Please check out the code below. I want to get the value entered in the prompt box into function dis(). How can I do that?
<!DOCTYPE html>
<html>
<head>
<script>
function display()
{
var z=prompt("enter your name...");
if(z!=null)
{
document.getElementById("demo").innerHTML="thankyou"+z+"..";
document.getElementById("case").style.display='block';
}
else
document.getElementById("demo").innerHTML="thankyou";
}
function dis()
{
var a=document.getElementById("aaa").value;
alert("your mark is"+a);
}
</script>
</head>
<body>
<p id="demo">click on the button.....</p>
<button type="button" onclick="display()">submit</button>
<div id="case" style="display:none">
<input type="text" id="aaa" name="myText" onDblClick="dis()">enter your mark
</div>
</body>
</html>
If you want to directly pass value to dis() function then change your script to
function display() {
var z = prompt("enter your name...");
if (z != null) {
document.getElementById("demo").innerHTML = "thankyou " + z + "..";
document.getElementById("case").style.display = 'block';
dis(z);
}
else
document.getElementById("demo").innerHTML = "thankyou";
}
function dis(arg) {
alert("your mark is" + arg);
}
If you want the value to be accessible from independent functions you'll need to store it in a global variable:
<script>
var userName = null;
function display() {
userName = prompt("enter your name...");
if (userName != null) {
document.getElementById("demo").innerHTML="thankyou "+userName +"..";
document.getElementById("case").style.display='block';
} else
document.getElementById("demo").innerHTML="thankyou";
}
function dis() {
var a=document.getElementById("aaa").value;
alert(userName + ", your mark is"+a);
}
</script>
Note that if the functions are completely independent they'll all need to test whether the variable has a value yet. In your case the dis() function is only called from a control that is made visible after a value has been set, but note that the user might click the button again and then cancel - in which case the name will be set back to null but the case element will still be visible.

Categories