Age verification, ensure is not blank and not less than 18 - javascript

it is supposed to make sure that the first 2 elem[0] and elem[1] are not blank and if they are to return and error or display the name
the second part is to give an error if the age, elem[2] is less than 18
function checkForm()
{
var elem = document.getElementById('myForm').elements;
if(elem[0].value or elem[1].value ==(""))
{
alert("Please enter your first and last name");
}
alert("Your name is " + elem[0].value + "" + elem[1].value);
if number(elem[2].value) < 18
{
alert("You are to young to be playing on this computer.");
}
alert("Your age is "+ elem[2].value);
}

looks like you aren't formatting your if() statements correctly.
instead of 'or', you should use || (two pipe symbols).
Also, correct format for the statement:
if(condition){
what to do if 'condition' is true
}
so, correct format:
if(elem[0].value =="" || elem[1].value ==""){
alert("Please enter your first and last name");
}
alert("Your name is " + elem[0].value + "" + elem[1].value);
use this formatting for your other code as well.

Your first conditional
if(elem[0].value or elem[1].value ==(""))
This error in this line stems from a colloquialism in English: when you say "the cat or the dog is here", this is a shortcut for the proper English, which is "the cat is here, or the dog is here".
Programming languages usually don't have colloquialisms; your code evaluates elem[0].value, then performs a boolean "or" operation on it with the expression elem[1].value == ("") as the other comparator.
That is, your line is equivalent to:
if ((elem[0].value) or (elem[1].value == ""))
and I think it's clear that this was unintended.
You probably meant to write:
if (elem[0].value == "" || elem[1].value == "")
Note that I've also replaced the non-existent or with ||, which means "or".
Your second conditional
In this line:
if number(elem[2].value) < 18
You forgot the surrounding ().
So:
if (number(elem[2].value) < 18)
Though it's not clear what you meant by number. Further study the text that instructed you to write that.
Other notes
Your indentation is generally messy.
I hope you are enjoying learning JavaScript. Keep reading your book and studying the syntax, because you generally have to get it precisely right: details matter!

try:
if (!isNaN(number(elem[2].value)) // its a number?
{
if (number(elem[2].value) < 18) // add ()
{
alert("You are to young to be playing on this computer.");
}
alert("Your age is "+ elem[2].value);
}

Related

how to make letter "s" equals to letter "z" in input prompt in javascript in html

i want to make the word brazil the same as brasil in this prompt
let country1 = "Brazil",
country2 = "Portugal";
if (
country.toLowerCase() === country1.toLowerCase() ||
country.toLowerCase() === country2.toLowerCase()
) {
alert("You speak Portugese.");
} else {
alert("You don't speak Portugese!");
}
how can i make s and z equals?
the alert "You can speak Portugese" will be display if "brasil" or "brazil" will be inputted.
This requirement is usually called “input sanitizing”. It means you take what you’ve got from the user and change it in such a way that it suits your needs. Upper-casing strings, removing excess whitespace, things like that.
In your case you could prepend a line country1 = country1.replace('razil', 'rasil'); and similar for country2 in front of the test. Then you only have to deal with a single spelling later.

How do I check if a variable is null, so that I can change it later on?

A group of me and two other people are working to make a Jeopardy game (themed around United States History questions) all in JavaScript. For our final Jeopardy screen, the two teams will each bet a certain amount of money. To prevent a team from typing in random letters for a bet (i.e typing in "hasdfhgasf" instead of an actual amount), we're trying to write an 'onEvent' command that checks to see if a bet is null. If that bet is null, then the code should come up with a message on the screen that tells them to check their bets again.
We tried using statements like, if "null" or if " " but neither of these statements works. We've worked with using getNumber and getText commands, along with just regular variable comparisons with or booleans. So far, we haven't had any luck with these methods.
Here's the group of code we're having issues with:
onEvent("finalJeopardyBetSubmit", "click", function() {
team1Bet = getNumber("team1BetInput");
team2Bet = getNumber("team2BetInput");
console.log(team1Bet);
console.log(team2Bet);
if (getText("team1BetInput") == "" || getText("team2BetInput") == "") {
console.log("Check bet!");
finalJeopardyError();
} else if ((getText("team1BetInput") != 0 || getText("team2BetInput") != 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") < 0 || getNumber("team2BetInput") < 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") > team1Money || getNumber("team2BetInput") > team2Money)) {
console.log("Check bet!");
finalJeopardyError();
} else {
console.log("Done");
}
});
You can also check out the whole program on Code.org if you'd like to get a better look.
We expect that with the console.log commands, it should say "check bet" if the bets return as null. Instead, the code has ended up fine, and not displaying our error message, even if we type in nothing or just random letters.
a null variable will evaluate to false. Try:
if(variable){
// variable not null
}else{
// variable null
}
Convert the value to a Number first using Number(value) and then check for falsy values using the logical not ! operator. If they enter alphabetic characters, then calling Number('abc') results in NaN.
If a value can be converted to true, the value is so-called truthy. If
a value can be converted to false, the value is so-called falsy.
Examples of expressions that can be converted to false are:
null; NaN; 0; empty string ("" or '' or ``); undefined.
The ! will change any of the falsy values above to true, so you can check for all of them with just the first if statement below.
onEvent("finalJeopardyBetSubmit", "click", function() {
// Convert these values to numbers first
var team1Bet = Number(getNumber("team1BetInput"));
var team2Bet = Number(getNumber("team2BetInput"));
if (!team1Bet || !team2Bet) {
// Handle invalid number error
}
else if (team1Bet < 0 || team2Bet < 0) {
// Handle invalid range error
}
else if (team1Bet > team1Money || team2Bet > team2Money) {
// Handle insufficient funds error
}
else {
// Finish game
}
})
You can read more about the logical operators here.

else statement within nested if statements. How does this code know which else statement to execute?

I get the nested if loops (same as using && operator), but how does this code here know which conditions to execute with no conditions and just back to back else statements? One of them is within the nested if statements. I can tell that's obviously why this works the way it does, I just don't get how. Also, I know how to write this in several more readable ways testing multiple conditions. Please just explain what is happening with this code here. How does it know to output "You are too old" or "You are too young?"
var age = prompt("Please enter Your age here :");
var min_age=18;
var max_age=40;
if(age>=min_age){
if(age<=max_age){
console.log("You meet the requirements for this competition");
}else{
console.log("You are too old");
}
}else{
console.log("You are too young");
}
The if-then-else ambiguity is known for a long time. All languages have solved it by defining that an else will match the first perceding if. So:
if (a)
if (b)
x = 1;
else
x = 2;
resolves to:
if (a) {
if (b) {
x = 1;
}
else {
x = 2;
}
}
EDIT by Nisar's reuest:
The if statement is defined as:
if (<condition>) <statement> [else <statement>]
This means that a <statement> in the above may also be an if statement. So, for example:
if (<condition>) if (<condition>) [else <statement>] [else <statement>]
As each else part is optional, the compiler has no way of knowing when it sees an else part to which if it belongs. To solve that the language defines that an else always matches the first preceding if.
The brackets {} set the limit.
Try to think in pseudocode, look beyond the characters and think about what is happening.
Reading in order:
If you are old enough
If your are not too old
'You meet the requirements for this competition'
OTHERWISE
'You are too old'
END
OTHERWISE
'You are too young'
END
Note how indentation can help see the limits of the conditions. Each indented part can be separated.
Firstly, let's indent your code.
var age = prompt("Please enter Your age here :");
var min_age = 18;
var max_age = 40;
if (age >= min_age)
{
if (age <= max_age)
{
console.log("You meet the requirements for this competition");
}
else
{
console.log("You are too old");
}
}
else
{
console.log("You are too young");
}
Starting off..
var age = prompt("Please enter Your age here :");
Let's say you enter 21 in the prompt box, so age=21
We initialize
var min_age = 18;
var max_age = 40;
Now let's look at the first if condition.
if (age >= min_age)
If you substitute the values,this translates to
if (21 >= 18)
This is true,therefore we go inside the if block and not to the else.
The next line is.
if (age <= max_age)
This translates to
if (21 <= 40)
Considering this is also true, we print You meet the requirements for this competition.
The most important take-away from this is, indent your code, and the rest becomes pretty simple.
There are just 3 Options
too young
correct age
too old
First Check - is the person old enough?
if(age>=min_age)
Second check - is the person too old?
if(age<=max_age)
the only possible option left after this if statment is FALSE :
too old

javascript isNaN() function not working?

I have a function to test if a prompt input is a number, like so:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?
NaN is a special value in Javascript. What isNaN does is check to see if the value passed is equal* to this special value. If you want to check if something is, say, not a stream of numbers, you can use a regular expression:
if (!/^\d+(\.\d+)?/.exec(person)) {
Or parse the value as a number and see if it converts back to the same string:
var n = parseFloat(person);
if (n.toString() !== person) {
*There's a reason that we don't use === but it's outside the scope of this answer.
The isNaN function checks if a value is NaN. NaN is a value that occurs when making operations that require numbers with non-numbers. Please see the documentation.
However the function does not check if the value is of type number. Too check if a value is of type number use the typeof operator
typeof person === 'number'
Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of IsNaN hasn't worked properly and I got around the problem by combining the parseInt method with the IsNaN method. According to the W3c web site (https://www.w3schools.com/jsref/jsref_isnan.asp) the IsNan('123') should return false and IsNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
Alternatively you can try this method which is well tested.
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
Hope this helps.

Checking if variable is an Integer in Javascript

I'm starting to learn JavaScript at school and one of the assignments require me to check user's input whether it is an Integer or not.
This code DOES NOT WORK FOR ME ON CHROME.
var person = prompt("Please enter your name", "Enter Name");
alert("Hello " + person);
var age = prompt("Please enter your age", "Enter age");
if (age == parseInt(age, 10))
alert("data is integer")
else
alert("data is not an integer")
Whether I enter a string or integer in my prompt box, it always display the "data is not an integer" message.
prompt will always return a string so in your case:
var integerAge = parseInt(age);
if(!isNaN(integerAge) && age === '' + integerAge)
alert("data is integer")
else
alert("data is not an integer")
In the case of an age, you'll also probably check it's a positive integer with some integerAge >= 0 or custom minimum and maximum in the next validation step.
Prompts always return strings, but since JS is loosely typed language, those Strings will get autocasted into Numbers when needed (Integers are called Numbers in JS), which is why your example works fine.
For a better check, you can use !isNaN.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
alert(!isNaN('10'));
alert(!isNaN('abc'));
alert(!isNaN(10));
For the lunatic downvoters, here's an optimized version of OP's code:
var age = parseInt(prompt("Please enter your age", "Enter age"), 10);
alert(isNaN(age) ? 'Not a number' : age);
You can try this one to check if its an integer:
function isInteger(x) {
return x % 1 === 0;
}

Categories