If else statement trouble javascript - 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!");
}
}

Related

if and else statement condition values not being recognized

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>

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>

Either document.location or window.location.href won't work in the if part of the condition, but will work on the else part

I use the following code to validate a password in a form. If the password is correct - Move the user to site X. If it's incorrect (after 3 tries), move the user to site Y.
For some reason, it works only for site Y.
My code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form>
Enter password to continue: <br>
<input type="text" id="user"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordValue = document.querySelector('#user').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
</script>
</body>
</html>
I tried doing:
Checking for syntax errors all over the code.
Changing === to == (I thought, maybe due to it being a string, the quote marks counted as well, of course I was mistaken).
window.location.href = 'http://maariv.co.il', true;
Adding return false right under window.location.href
As a beginner I ask, why would the condition works only in a half? That is, the positive part (than) doesn't work but the negative part (else) does work.
Update:
This is just an exercise. Indeed. This isn't going to production. In production I should store and request the password from a database.
Put the following line let passwordValue = document.querySelector('#user').value; inside onclick of "mybutton".
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordInput = document.querySelector('#passwordInput').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
<form>
Enter password to continue: <br>
<input type="text" id="user" />
<input type="button" id="myButton" value="Enter site" />
</form>
Use return :
if (password === passwordValue) {
return window.location.href = 'http://maariv.co.il';
}
Otherwise, the function will execute to the end, and you will reach the second redirection, that will then override the first one.

How do I get the values in PROGRAM 2 to apply to printing in the console?

Okay so I technically have everything working in the program, but I need to permanently change the values of the array that I create in PROGRAM 2 and add -blip and -clang. What do I call upon to change the values so that I can call them to the console in PROGRAM 3? I can't have anything in the body so innerHTML and document.write are out of the question(which sucks). Problem area is marked with a comment on line 37 to make it easier to find.
<!DOCTYPE html>
<html>
<head>
<title>Project 1 – Michael Fiorello</title>
<p id="demo"></p>
<script>
do {
//MAIN MENU
var input = prompt("Please enter 1, 2, 3, or exit.");
{
//PROGRAM 1-Enter the string to be converted to robot speak
if (input === "1")
do {
var one = prompt ("Please enter a string.");
{
if (one === "")
{
console.warn("You need to enter something");
}
}
} while (one === "")//keep repeating program 1 until something is entered, aka cannot be blank.
//PROGRAM 2-Convert the string into robot speak
else if (input === "2")
{
if (one == null) {
console.warn ("You need to first enter a String");
}
else
{
console.log ("String Converted")
var res = one.split(" ");
for(i = 0; i<res.length; i++)
if(res[i].length >= 5)
//What do I do here to change the value of entered strings in the array, rather than just write it out?
{
document.write(res[i]+"-blip ");
}
else
{
document.write(res[i]+"-clang ");
}
}
}
//Program 3 Robot Language version of the string will appear in the console
else if (input === "3")
{
var output = res.join(" ");
alert ("AWESOME!");
console.log (output);
}
else if (input == null|| input.toLowerCase() == "exit")
{
alert ("Thanks for using the ROBOT Language Converter!");
}
else
{
alert ("Nope");
console.warn("You need to enter something");
}
}
} while(input.toLowerCase() != "exit");
</script>
</head>
</html>
It was so simple that I feel like an idiot. All I had to do was change the document.write lines to
res[i] = (res[i]+"-blip ");
and it changes the values to what I need.

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