Here is my current code:
if (ageCheck < 18) {
alert("YOU ARE TOO YOUNG");
} else if (ageCheck => 18) {
alert("WELCOME");
} else {
alert("test");
}
ageCheck();
The problem is that when running this and I put in random words rather then give me "test" it gives me "Welcome". How do I make it so that when I enter in something other then a number it runs the else part and gives me "test"?
Why don't you add ane more check first, before comparing the number with 18?
if(isNaN(parseInt(ageCheck))) alert('not a number')
Change else if statement to,
} else if (ageCheck >= 18) {
greater than or equal to is represented by >=
Maybe the below function can help you
if (isNaN(ageCheck)) {
alert("test"); }
else if (ageCheck < 18) {
alert("YOU ARE TOO YOUNG");
} else if (ageCheck >= 18) {
alert("WELCOME");
}
isNaN will check, whether its a number or not first
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.
I ran the following code in Google Chrome Version 54.0.2840.100 (64-bit). It displays an alert dialog successively asking for input until the user enters the correct answer, but the problem is that when i click the close button or cancel button in the alert dialog instead of closing, it continues asking for input.Also the close button on the tab is unclickable.Nevertheless I can close chrome main window but is there a code to correct this.
var answer = Number(Math.floor(Math.random()*10));
do{
var number = Number(prompt("Guess a number"));
if(number-answer >10){
alert("Too big!!");
}
else if(number-answer < 10 && number>answer ){
alert("It's bigger, but you are close!");
}
else if(answer-number < 10 && number<answer){
alert("It's smaller, but you are close!");
}
else if(answer-number > 10){
alert("Too small!!");
}
else if(number==answer){
alert("You WIN !!");
break;
}
}while(number!=answer);
The easiest and straightforward answer would be to remove the do...while loop. 'coz that would keep the code running till you input the right answer.
So, you could check for the inputed number, if it is null break it, else convert it to your number and run the loop.
checking for null firsthand would make it easy to check for 0 as an input too
var answer = Number(Math.floor(Math.random()*10));
do{
var number = prompt("Guess a number");
if(number!=null){
number = Number(number);
} else {
break;
}
if(number-answer >10){
alert("Too big!!");
}
else if(number-answer < 10 && number>answer ){
alert("It's bigger, but you are close!");
}
else if(answer-number < 10 && number<answer){
alert("It's smaller, but you are close!");
}
else if(answer-number > 10){
alert("Too small!!");
}
else if(number==answer){
alert("You WIN !!");
break;
}
}while(number!=answer);
var answer = Number(Math.floor(Math.random()*10));
do{
var number = Number(prompt("Guess a number"));
if(number === 0){ // this check is needed
break;
}
if(number-answer >10){
alert("Too big!!");
}
else if(number-answer < 10 && number>answer ){
alert("It's bigger, but you are close!");
}
else if(answer-number < 10 && number<answer){
alert("It's smaller, but you are close!");
}
else if(answer-number > 10){
alert("Too small!!");
}
else if(number==answer){
alert("You WIN !!");
break;
}
}while(number!=answer);
on closing the prompt, null is returned
passing null to Number function will return 0
hence the check for 0 is added
you could also modify the code as follows to allow 0 as input from the user
var input= prompt("Guess a number");
if(input === null){
break;
}
var number = Number(input);
... rest of the code
If click cancel, the input value will be null, then Number(null) will be 0.Unless the guess number is 0, the alert dialog would not be closed.
You'd better check the input value is null before cast it.
Window.prompt()
I have added a line of code to check whether user has cancelled the prompt.
var answer = Number(Math.floor(Math.random()*10));
do{
var number = Number(prompt("Guess a number"));
// Add the below code to check for null and exit
if (number === null)break;
// END
if(number-answer >10){
alert("Too big!!");
}
else if(number-answer < 10 && number>answer ){
alert("It's bigger, but you are close!");
}
else if(answer-number < 10 && number<answer){
alert("It's smaller, but you are close!");
}
else if(answer-number > 10){
alert("Too small!!");
}
else if(number==answer){
alert("You WIN !!");
break;
}
}while(number!=answer);
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');
}
Why won't my nested if/else statements work: it takes me to bing.com as a search engine no matter what adult age I enter; everything else works correctly.
function adult_jump(SelectSE, SelectWD, age) {
if (SelectSE==true) {
if (age <= 45) {
window.location = "http://www.google.com"
} else {
window.location = "http://www.bing.com"
}
} else {
if (SelectWD==true) {
window.location = "http://www.yahoo.com"
} else {
window.alert("You must select a search tool!")
}
}
}
while comparing with true or false.. it is better to use the === operator.. i modified the window.location to alert.. so you can see all results at once here
function adult_jump(SelectSE, SelectWD, age) {
if (SelectSE === true) {
if (age <= 45) {
alert("http://www.google.com") ; }
else { alert("http://www.bing.com") ; }
}
else {
if (SelectWD === true) {
alert("http://www.yahoo.com") ; }
else { alert("You must select a search tool!") ;}
}
}
adult_jump(true,false,30); // alerts google
adult_jump(true,false,48); // alerts bing
adult_jump(false,true,0) ; //alerts yahoo
adult_jump("","",0) ; // alerts select a search tool
this is my first question on stack overflow, I have only been coding for a few months and I know I am probably just missing something simple here. I am trying to create a simple program for learning purposes, computer auto picks number between 1-100, user then picks number and is alerted if their choice is hot or cold in relation to the computer number.
I am trying to pass the users answer from a form field into a JavaScript variable, then run the function to test their answer when a button is clicked. I am using jQuery for both of these.
Here is the application live: http://keithlamar.github.io/HotOrCold/
Here is my HTML:
<form>
Your Number <input id="guess" type="number" name="yournumber"><br>
</form>
<p id="pick">Click Here</p>
Here is my JavaScript:
var userNum = $('#guess').val();
var comNum = Math.floor(Math.random()*101);
var difference = function (a,b) {return Math.abs(a - b)};
var askNumber = function(){
if(userNum == comNum){
alert("You got it! You Win!")
}
else if(difference(userNum,comNum) < 5){
alert("Very Hot!");
}
else if(difference(userNum,comNum) < 10){
alert("Hot!");
}
else if(difference(userNum,comNum) < 20){
alert("Warm!");
}
else if(difference(userNum,comNum) > 20){
alert("Very Cold!")
}
else {
alert("Sorry, you need to choose a number.")
}
};
$(document).ready(function(){
$('#pick').click(function(){
askNumber();
});
});
It seems like the var userNum is not getting a value from the input. I think it may have something to do with nesting of functions within functions, but I am not entirely sure!
Thanks for any input!!
You need to read the values inside the function - in your code you are reading the input field during the page load(before the click happens)
function difference(a, b) {
return Math.abs(a - b)
};
function askNumber() {
//read the user input in the click handler
var userNum = parseInt($('#guess').val(), 10);
var comNum = Math.floor(Math.random() * 101);
//calculate the difference only once then reuse it
var diff = difference(userNum, comNum);
if (diff == 0) {
alert("You got it! You Win!")
} else if (diff < 5) {
alert("Very Hot!");
} else if (diff < 10) {
alert("Hot!");
} else if (diff < 20) {
alert("Warm!");
} else if (diff > 20) {
alert("Very Cold!")
} else {
alert("Sorry, you need to choose a number.")
}
};
$(document).ready(function () {
$('#pick').click(function () {
askNumber();
});
});
Demo: Fiddle