Checking if variable is an Integer in Javascript - 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;
}

Related

Trying to create a JavaScript popup box

I am supposed to provide messages if the variable entered is higher or lower than a specific number.
I'm using the if statement to do this, but after the value is entered and the correct message is shown, the second 'if' statement is run too, I don't want this to happen. I've tried using the 'else' statement in place of the second 'if' statement, but it doesn't seem to work.
Here is my code
<script type="text/javascript">
var a, name;
name = window.prompt("Please enter your first name", "First Name");
a = window.prompt("Enter a number from 1-100", "1-100");
a = parseInt(a);
myFunction (a, name);
function myFunction(a, name) {
if (a <= 50) {
alert("Hey your number is less than 50");
}
if (a < 100) {
alert("Your number is higher than 50")
}
}
</script>
Please forgive me as I'm quite new to all of this.
thank you all
Thie if-else works perfectly fine for me
<script type="text/javascript">
var a, name;
name = window.prompt("Please enter your first name", "First Name");
a = window.prompt("Enter a number from 1-100", "1-100");
a = parseInt(a);
myFunction (a, name);
function myFunction(a, name) {
if (a > 0 && a <= 50) {
alert("Hey your number is less than 50");
}
else if(a <= 100){
alert("Your number is higher than 50")
}
else {
alert("Invalid number");
}
}
</script>
Again, if you look at your if conditions, both are true so it shows both the alerts.
The problem is that even if you put else if after the if statement it will also give a msg since for an example , if 40 <=50 , msg will popup .. and also 40 < 100 is true so the msg also will popup !
correct way :
if (a <= 50) {
alert("Hey your number is less than 50");
}
else if (a<=100) {
alert("Your number is higher than 50")
}

How to create Alert pop up that shows text based on Prompt input type?

I am a beginner experimenting with some basic Javascript.
My goal is to show a (1.) prompt message (requesting a name) followed by an (2.) alert based on the prompt input. If the prompt input is a valid name (string) then an alert box should appear with text "thank you" + name. Else the alert should appear with the text "you didn't enter a valid name".
The 1. prompt message is working, however, the 2. alert message shows me the same text whether i enter a name/text or a number. In other words the alert message is not distinguishing between text string or number and is always showing the text "thank you" + name.
this is my code:
function EnterName() {
var name = prompt("Enter your name here:");
if (typeof name === "string") {
alert("thank you " + name);
} else if (typeof name === "number") {
alert("you didn't enter a valid name");
}
}
console.log(EnterName());
Would appreciate any insights in how to make the alert box show "you didn't enter a valid name" when a number is entered in the prompt box.
Thanks.
Prompt always returns a string, you could try to convert it to a number and then check to see if it NaN's on you which means it's a string. It would be better to use a regexp here though. You may also want to return the name if you are logging it.
function EnterName() {
var name = prompt("Enter your name here:");
var isNum = !isNaN(Number(name));
if (!isNum) {
alert("thank you " + name);
} else {
alert("you didn't enter a valid name");
}
return name;
}
console.log(EnterName());
You always enter strings into prompts. SO you can try to make it a int below and if it succeeds then give an error message otherwise say hello.
function EnterName() {
var name = prompt("Enter your name here:");
if(parseInt(name)) {
alert("you didn't enter a valid name");
}
else if (!parseInt(name)) {
alert("thank you " + name);
}
}
prompt method parameters type are alway String, no matter what you enter, your condition will always true :
//text & defaultText types are String
`prompt(text, defaultText)`
So you need to change your condition. One solution is using regex for example you can change your code to this :
function EnterName() {
var name = prompt("Enter your name here:");
!name.match(/^\d+$/) ?
alert("thank you " + name)
:
alert("you didn't enter a valid name");
}
console.log(EnterName());
Basically !name.match(/^\d+$/) will check if input data is number or not and based on that will show the alert messages.
https://jsfiddle.net/6mxL59k0/1/
So, one thing I want to emphasize is how you are approaching solving this problem. You are looking at your problem thinking, "If I type in a number, this should be false! Why isn't it working?!". The reason why is because prompt will always return a value that is typed to a string. You are looking to see if there is a number or an int depending on the language.
So, we can break this into two problems. See if this guy is a string, see if that string contains a number
The code below shows a great way to do that using two functions
function enterName() { // Javscript functions should always start with a lowercase unless it is a function express and can be invoked using the `new` keyword
var name = prompt("Enter your name here:");
if (!checkIfContainsNumber(name)) {
alert("thank you " + name);
} else { // if f we dont have a number, we have a valid name, otherwise we are invalid!
alert("you didn't enter a valid name");
}
}
So we have our main function, it takes in the promp which always returns a string
// this solves problem 2, seeing if we have a number inside of our string
function checkIfContainsNumber(myString) {
return /\d/.test(myString);
}
enterName();
our second function checkIfContainsNumber solves part 2 of our problem using a regex expression that matches for a digit (d in this case)

Code in Javascript, using if, else and prompt.

I am trying to write a code to answer the following. I have options of prizes. To be eligible for the prizes, you need to be within the age range of 20 and 40. If you are not eligible an alert saying you are not eligible will appear. If you are eligible; prompt will ask you for which prize you want and you need to answer with a numeric value. After they answer they will receive an alert that says "You will receive (prize, collected from the array) in your post within 2 weeks."
I have gotten this far with my code:
var prize = [
"0 = iPhone",
"1 = iPad",
"2 = iMac",
"3 = iPod"
];
var age = prompt("Please enter your age");
if (20 >= age && age <= 40){
alert("Sorry, you are not eligible for a prize.");
} else {
prompt("Which prize would you like to receive?");
} else if {
Would someone want to give me a hand? Thanks :)
You have mixed up a lot of the logic there, and actually put the "success" code within the "failure" condition.
I have no idea what you intend to do with the second prompt to choose the prize - and have even less clue why someone's age is the limiting factor in being eligible for a prize - but here is some logic that will correctly filter your desired age range:
var age = prompt("Please enter your age");
if (age >= 20 && age <= 40){
// handle successful prize claim here
}
else {
alert("Sorry, you are not eligible for a prize.");
}

Have been scanning for NaN and getting lost

I am defining a function that takes three numbers as arguments and returns the largest of them.
Here is my code:
var instructions = alert("Choose a set of numbers to input for the computer to determine which value is the largest");
var inputOne = prompt("Please input your first desired value");
var inputTwo = prompt("Please input your second desired value");
// THIS ARRAY STORES THE VALUES OF inputOne && inputTwo
var maxInput = Math.max([inputOne, inputTwo]);
var inputThree = prompt("Please input your third desired value");
// THIS WILL COMPARE BETWEEN THE inputThree && THE MAX INPUT OF THE USERS FIRST TWO CHOICES
var maxNumber = Math.max(maxInput, inputThree);
//validate if inputs are numbers and not letters
// isNaN()
var compare = function (maxNumber, inputThree) {
if (inputThree === maxNumber) {
return alert("The result is the same!");
} else if (inputThree != maxNumber) {
return alert(maxNumber + " " + "is the larger value!");
}
}
compare(maxNumber, inputThree);
Now I'm getting a result of "NaN is the larger value!" and it's driving me crazy! I tried running console.log to see where I'm getting NaN but that didn't work at all. All that did was log NaN to the console.
I also tried taking the parameters out of Math.max( ) however was just getting:
"-infinity is the larger value!"
Can someone at least give me a hint as to why this is happening? Or explain to me further what is going on.
Math.max([inputOne, inputTwo]) should be Math.max(inputOne, inputTwo)
Why don't you just get the largest of all of them with just
var maxNumber = Math.Max(inputOne, inputTwo, inputThree);
Here:
var inputThree = prompt("Please input your third desired value");
inputThree is a String (i.e. its value has a Type of String), always. And here:
var maxNumber = Math.max(maxInput, inputThree);
maxNumber is a Number, always (because that's what Math.max returns, even though the arguments are Strings). So:
inputThree === maxNumber
is always false, because a Number is never equal to a String (see the Strict Equality Comparison Algorithm). So either convert inputThree to a Number, e.g.
+inputThree === maxNumber
or use ==.
inputThree == maxNumber

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

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);
}

Categories