I am writing this basic control structure for a lesson and I am getting some unexpected behavior.
var answer = prompt('what is your age');
if (answer >= 21) {
alert('good to go!');
}
else if (answer < 21) {
alert('sorry not old enough');
}
else if (answer != typeof Number) {
alert('please enter your age as a number');
}
else if (answer === null) {
alert('you did not answer!');
}
On the very last conditional, I would expect that if I left the prompt empty, it would execute the last alert. However, it just says 'not old enough'. Is it treating no input into the prompt as 0? How can fix this?
Thanks.
Prompt doesn't return null if the user hits OK, to test for emptiness, you need to check if the string is empty answer === ""
You need to move the last two checks to the top since "" < 21 is true:
var answer = prompt('what is your age');
if (answer === '') {
alert('you did not answer!');
} else if (isNaN(answer)) {
alert('please enter your age as a number');
} else if (answer >= 21) {
alert('good to go!');
} else if (answer < 21) {
alert('sorry not old enough');
}
Related
So I made a form in a table in html and the javascript code checks till the (creditcard.value.length) after that the code doesn't check anything
<script language="javascript" type="text/javascript">
function ispsd(form) {
var passed = false;
if (form.Fullname.value.length < 4) {
alert("Enter a valid Full Name");
} else if (form.Email.value.indexOf("#") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Email.value.indexOf(".") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Cardholder.value.length < 3) {
alert("Card Holder name is not Valid.")
} else if (form.Creditcard.value.length != 16) {
alert("Credit card number is not valid.")
} else if (isNan(form.Creditcard.value)) {
alert("Credit card number cannot contain letters.")
} else if (isNan(form.Zip.value)) {
alert("Enter a valid Postal Code.")
} else if ((form.Expyear.value) * 1 < 2021) {
alert("Credit Card has Expired.")
} else if (isNan(form.Expyear.value)) {
alert("Enter a valid Year.")
} else if (form.cvv.value.length != 3) {
alert("Enter a valid CVV.")
} else if (isNan(form.cvv.value)) {
alert("CVV cannot contain letters.")
} else {
passed = true;
}
return passed;
}
</script>
and the thing is when I moved the (form.Expyear.value) * 1 < 2021) above the (form.Creditcard.value.length != 16) the validation worked and when I tried to add all the (else if) above the Credit card check it didn't work
don't know what's the problem
if anyone can help I would be thankful
You can always use console.log() to check what the variable has
function validate(form) {
if (form.Fullname.value.length < 4) {
alert('Enter a valid Full Name');
document.form.Fullname.focus();
return false;
}
if (form.Email.value.indexOf('#') == -1 || form.Email.value.indexOf('.') == -1) {
alert('Enter a valid E-mail adress.');
document.form.Email.focus();
return false;
}
if (form.Cardholder.value.length < 3) {
alert('Card Holder name is not Valid.');
document.form.Cardholder.focus();
return false;
}
console.log(form.Creditcard.value);
if (isNaN(form.Creditcard.value)) {
alert('Credit card number cannot contain letters.');
document.form.Creditcard.focus();
return false;
}
if (form.Creditcard.value.length < 16) {
alert('Credit card number is not valid.');
document.form.Creditcard.focus();
return false;
}
if (isNaN(form.Zip.value)) {
alert('Enter a valid Full Name');
document.form.Zip.focus();
return false;
}
if (isNaN(form.Expyear.value)) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (Number(form.Expyear.value) < 2021) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (isNaN(form.cvv.value)) {
alert('CVV cannot contain letters.');
document.form.cvv.focus();
return false;
}
if (form.cvv.value.length != 3) {
alert('Enter a valid Year.');
document.form.cvv.focus();
return false;
}
return true;
}
Try to remove the * 1, not sure what's the purpose there
isNaN, and not isNan
I would also handle it differently, what you need is to return true if they pass, rather than identify errors, for example, the demo here below. For example, it will pass your test if you have more than 16 numbers since you're checking x !== 16
function validate() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("cc").value;
// If x is Not a Number or less than one or greater than 10
if (!isNaN(x) && x.length > 3 && x.length <= 16) {
text = "Input OK";
} else {
text = "Input not valid";
}
document.getElementById("error").innerHTML = text;
}
<p>Please write only numbers, from 4 to 16 maximum characters</p>
<input type="number" id="cc"/><br>
<span id="error"></span><br>
<input type="submit" onclick="validate()" />
Last but not least, this is so verbose and difficult to maintain, I strongly suggest using a library like this one https://www.npmjs.com/package/validator to handle validation, or even jQuery has .validate() useful function for beginner.
how to tell javascript that the user enter a string in the prompt box and work with it in an if statment ? If the user enters a string of letters I want it to alert "You did not enter a number", and if they entered a string if digits then continue with the logic.
var userGess = prompt("guess a number");
var secretNumber = 7;
if (Number(userGess) > secretNumber) {
alert("the number is to high")
} else if (Number(userGess) < secretNumber) {
alert("the number is to low")
} else if (Number(userGess) == secretNumber) {
alert("you are correct")
} else if (userGess == toString(userGess)) {
alert("you didnt type a number")
}
You can use isNaN(userGess) to check if a given string userGess is non-numeric.
However, that returns false if userGess is empty string, so you have to explicitly check it. So your final condition becomes
userGess === "" || isNaN(userGess)
var userGess = prompt("guess a number");
var secretNumber = 7;
if(userGess === "" || isNaN(userGess)) {
alert("You didn't enter a number")
} else if (Number(userGess) > secretNumber) {
alert("the number is to high")
} else if (Number(userGess) < secretNumber) {
alert("the number is to low")
} else if (Number(userGess) == secretNumber) {
alert("you are correct")
}
I am making a little 'guess the number' game, and I need to find a way to repeat the function based on what it outputs. What I have right now is this:
var input = prompt("Please enter a number between 1 and 100!");
var ranNum = Math.floor(Math.random()*100);
function numCheck()
{
if (input < 1)
alert("Please enter a valid number!");
else if (input > 100)
alert("Please enter a valid number!");
else if (input > ranNum)
alert("Try a little lower!");
else if (input = typeof stringValue)
alert("That is not a number!");
else if (input < ranNum)
alert("Try a little higher!");
else
alert("You got it!");
}
numCheck();
I did this using the inspect option on chrome on the page about:blank. Now that I have the function, I think I need to use another if else statement. It would detect if numCheck() output is You got it!" and if it didn't, it would replay the numCheck function, all the way until the player got the correct number.
How would I do it like that? And if there is a simpler way, what is it?
I made a fiddle that will use alerts and prompt accessible inside the page (I am not sure this what you asked for or not - explain more if not):
HTML:
<div class="numberguess">
<input type="text" id="entry" value="" />
<input type="button" id="send" class="" value="submit" />
</div>
<div id="alert"></div>
JS:
var _alert = document.getElementById('alert');
var ranNum = Math.floor(Math.random()*100);
function numCheck(){
var input = document.getElementById('entry').value;
if (input < 1 && input > 100)
_alert.innerText = "Please enter a valid number!";
else if (input > ranNum)
_alert.innerText = "Try a little lower!";
else if (typeof input != 'string')
_alert.innerText = "That is not a number!";
else if (input < ranNum)
_alert.innerText = "Try a little higher!";
else
_alert.innerText = "You got it!";
}
numCheck();
var el = document.getElementById('send');
el.addEventListener('click', function(){
numCheck();
}, false);
Check this as live exp: Jsfiddle
you can use looping like this code below
var input; // var to hold user input
var ranNum = Math.floor(Math.random()*100);
var win = false; // var if we want to ask another input
var trycount = 0; // don't want to ask for input forever
function numCheck()
{
if (input*1 != input) // check if number first
alert("That is not a number!");
else if (input < 1) // check lower bound
alert("Please enter a valid number!");
else if (input > 100) // check upper bound
alert("Please enter a valid number!");
else if (input > ranNum) // tell a hint
alert("Try a little lower!");
else if (input < ranNum) // tell a hint
alert("Try a little higher!");
else{
alert("You got it!");
win = true; // end the user prompt
}
}
while (!win && trycount < 3){ // while wrong guesses and below 3 tries
input = prompt("Please enter a number between 1 and 100! (" + ranNum + ")");
trycount++; // count the try
numCheck();
}
You need a looping mechanism that will keep prompting the user to input another value.
var ranNum = Math.floor(Math.random()*100);
function numCheck()
{
var input = prompt("Please enter a number between 1 and 100!");
if (input === null)
return false; // user pressed "cancel"
if (input == ranNum) {
alert("You got it!");
return false;
}
if (input < 1)
alert("Please enter a valid number!");
else if (input > 100)
alert("Please enter a valid number!");
else if (input > ranNum)
alert("Try a little lower!");
else if (input < ranNum)
alert("Try a little higher!");
else
alert("That is not a number!");
return true; // continue looping
}
while(numCheck());
I'm making a JavaScript project and I want to alert when the user enters nothing in the prompt
function verifyage() {
var age = prompt("enter your age:", "");
var status = (age >= 18) ? "adult" : "minor";
if(status == "minor") {
alert("you are too young");
} else if (status == "adult") {
alert("you're in");
} else if (status == "null") {
alert("you need to enter your age");
}
else {
void(0);
}}
<button onclick="verifyage();" type="button">watch movie</button>
What it's supposed to do:
define a variable age which defines the age of user
define a variable status which has two value adult and minor
prompt for the age of the user
alert the message you are too young when the user enter a number less than 18
alert the message you're in when user enters number greater than 18
alert the message you have to enter your age when user enters nothing
But when I test it and enter nothing it says you are too young - why?
I tried how to show alert when user enter other then number value in textfield and other but nothing.
EDIT:When i press cancel it says you are too young...help?
It seems to me that you want to continue to prompt the user to enter something into the field. To accomplish that I would have a while loop that checks to make sure the age is not blank. It also looks unnecessary to set status to then just check for the value when you could just check the age.
function verifyage() {
var age = prompt("enter your age:", "");
//var status = (age >= 18) ? "adult" : "minor";
while(age === "" || isNaN(age)){
age = prompt("enter your age:", "");
}
if(age <= 18) {
alert("you are too young");
} else if (age > 18) {
alert("you're in");
}
else {
void(0);
}
}
function verifyage() {
var age = prompt("enter your age:", "");
if(isNaN(parseFloat(age))) { // check: if user entered a number/string/blank
alert("You entered nothing");
}
else {
var status = (age >= 18) ? "adult" : "minor";
if(status == "minor") {
alert("you are too young");
} else if (status == "adult") {
alert("you're in");
}
}
}
verifyage();
I am no javascript expert, but looking at your code I think "null" will not do what you want it to. Right now it is explicitly looking for the typed text "null". In c++ for example you could use
else if (status == "")
or (maybe even better) just use else (so that everything except for adult/minor could give an error)
Also I would not make the comparison with the variable "status", but with "age". This should be the first comparison you make. When the typed age == "" ( <- nothing) then you could give an alert, prompting the user to type their age again.
Good luck!
Please see the below correction, You were running into trouble since when you do enter, the value of your age variable was 0.
function verifyage() {
var age = prompt("enter your age:", "");
var status = (age >= 18) ? "adult" : "minor";
if (age == 0)
status = "null";
if(status == "minor") {
alert("you are too young");
} else if (status == "adult") {
alert("you're in");
} else if (status == "null") {
alert("you need to enter your age");
}
else {
void(0);
}}
<button onclick="verifyage();" type="button">watch movie</button>
function verifyage() {
var age = prompt("enter your age:", "");
if(age=='' || age<="0" || isNaN(age)){alert ("you have to enter your age");
}
var status = (age >= 18) ? "adult" : "minor";
if(status == "minor") {
alert("you are too young");
} else if (status == "adult") {
alert("you're in");
} else if (status == "null") {
alert("you need to enter your age");
}
else {
void(0);
}}
First of all if you don't select the age it will assign it to 0 which is under 18 the first if will obtain so to avoid that add if statement to validate if the user don't write anything or write 0 by error like the code above
I am getting value from a text field. I have one if and several else if statement.
The problem the last else if doesn't execute even if the condition is true.
If I change the last else if to if it executes and gives alert. When I change that back to else if the statement doesn't execute. The else if before that is fine as it's firing/executing on a particular condition.
function Valcheck()
{
var txtVal = document.getElementById("sometextField").value;
if(txtVal =="%")
{
alert("% is only allowed with other characters.");
return;
}
else if(txtVal.indexOf("%") != -1)
{
if((txtVal.indexOf('%')) != (txtVal.length-1))
{
alert(" % is only allowed at the end.");
return;
}
}
else if(txtVal.indexOf(",") != -1)
{
alert("Comma or comma separated values are not allowed.");
return;
}
else if(( txtVal.length >0) && (txtVal.indexOf("%") == -1))
{
alert("Please enter % at the end of the value.");
return;
}
else if( txtVal.length > 11 )
{
alert(" Value can't be greater than 11 characters.");
return;
}
}
Please help. Thanks
The problem is that if txtVal.length > 11, then either this is met:
else if(txtVal.indexOf("%") != -1)
or this is met:
else if(( txtVal.length >0) && (txtVal.indexOf("%") == -1))
So that it will never reach the else if( txtVal.length > 11 ). You need to change this:
else if(txtVal.indexOf("%") != -1)
{
if((txtVal.indexOf('%')) != (txtVal.length-1))
{
alert(" % is only allowed at the end.");
return;
}
}
to this:
else if(txtVal.indexOf("%") != -1 && txtVal.indexOf('%') != (txtVal.length-1))
{
alert(" % is only allowed at the end.");
return;
}
so that it doesn't "capture" the case where txtVal.indexOf('%') == (txtVal.length-1).
There isn't a limit to the number of if statements. The issue is that one of the previous if statements catches the case you're testing.
Go through each if statements for the case your testing and see if it's beging caught by a previous one.
This happens because your else if(txtVal.indexOf("%") != -1) is true (so, second if from the top), but condition for "if" inside it is not true (so it doesn't go to "return".
there is no way that the last 'else-if' be hit:
if the textVal has a '%' in it it will go to the second 'else-if'
and if it does not have '%' it will go to the one before the last one.
so the last if never be hit.
There is no limit to if else nesting. There is a logical barrier to getting to nested if else clauses. Look into using
switch(caseVariable){
case 1: document.write("caseVariable = " + 1);
break;
case 35: document.write("caseVariable = " + 35);
break;
default: break;
}