how to check if an input is a number in js - javascript

here is the code I've been working on.
var storeUsersInfo = [];
var amountOfUsers = prompt("How many users do you want?");
amountOfUsers = parseInt(amountOfUsers);
function returnUserInput() {
var askFirstName = prompt("What is your first name?");
var askLastName = prompt("What is your last name" + " " + titleCase(askFirstName) + "?");
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
if(askAge != int) {
alert("Not a valid input")
};
return {
firstName: titleCase(askFirstName),
lastName: titleCase(askLastName),
age: askAge
};
};
function titleCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
for(var i = 0; i < amountOfUsers; i++) {
storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);
I wondering how I can check the input of askAge to see if it equals a number.
I tried some code as you can see on lines 9-12 and I can't figure it out. I know it has to do something with typeof.
Thoughts?

multiply it by 1 and if it returns NaN and is not the same as the original input- its not a number
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
var askedAge=parseInt(askAge)*1;
if(askedAge != askAge) {
alert("Not a valid input");
}

This can be solved using a combination of Number.isInteger and Number.parseInt. Both of which have been standardized in ES2015.
The following expression will check if the age is valid:
Number.isInteger(Number.parseInt(askAge));
Note that you'll have to parse the user input to an integer first; this can either result in a valid integer or in NaN.
If it is an integer, then Number.isInteger will make the expression true; otherwise, the parsed number was NaN and the expression will become false.

I think you can you this code,
function isNumeric(x) {
return !isNaN(parseFloat(x)) && isFinite(x);
}

You could use
Number.isInteger(askAge)
Reference :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger

try this
var check = /^[0-9]+$/;
var checkall = askAge.match(check);
if (!checkall){
alert("Not a valid input")
}

The cryptic answer:
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
if(!Number.isInteger(Number.parseInt(askAge))) {
alert("Not a valid input")
};
More:
You are partially correct in your assumption, you do have to check the type of the number to ensure that is is a number and also that it is an integer. How you actually DO that has several options. Here is one that should work.
You must determine if you wish to use Number() or Number.parseInt() as that determination will herein make a difference in the accepted values.
Given that, I choose to use the parseInt in this answer. I also constructed it to not accept 0 as a value for the number of users.
First we use or create the isInteger and parseInt in Number:
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
};
Number.parseInt = Number.parseInt || parseInt;
Declare our other functions: (commented)
// this will error out if "Cancel" on the prompt is clicked (null is passed in mystring)
function titleCase(mystring) {
return mystring.charAt(0).toUpperCase() + mystring.slice(1);
}
function returnUserInput() {
var isValid = false;
var askFirstName = "";
var askLastName = "";
var askAge = null;
do {
askFirstName = prompt("What is your first name?"); // currently accepts " " as a valid name
askLastName = prompt("What is your last name" + " " + titleCase(askFirstName) + "?"); // accepts " " as a valid name
askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
isValid = Number.isInteger(Number.parseInt(askAge));
if (!isValid) {
alert("Not a valid input");
}
} while (!isValid); // accepts 0 and negative values as age
return {
firstName: titleCase(askFirstName),
lastName: titleCase(askLastName),
age: Number.parseInt(askAge) // was using the unparsed string "4' if 4 was entered
};
}
Use the functions:
var storeUsersInfo = [];
var amountOfUsers = 0;
var enteredCount = 0;
do {
amountOfUsers = prompt("How many users do you want?");
enteredCount = Number.parseInt(amountOfUsers, 10);// parse it
} while (!(Number.isInteger(Number.parseInt(amountOfUsers, 10))) && !enteredCount > 0)
amountOfUsers = enteredCount;
for (var i = 0; i < amountOfUsers; i++) {
storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);// console.dir might also work (better?)

Related

My while loop is not displaying any outputs after making a search from the arrays

I'm able to run it, fill out both Arrays, then input the search criteria but that's it. no results are thrown back.
var SIZE = 4;
var actors = new Array(SIZE); //array holding actors
var roles = new Array(SIZE); //array holding roles
for (var i = 0; i < SIZE; i++) {
actors[i] = prompt ("Please enter your " + (i + 1) + " favorite Actor");
roles[i] = prompt ("What role did your " + (i + 1)+ " Actor played?");
}
var favorite; // hold search actor name
var found = false;
var BR = "<br>";
favorite = prompt ("Please enter the name of your most favorite actor of all");
while (i < size && !(found)) {
i++;
if (actors[i] == favorite) {
found = true;
document.write("Your favorite actor " + actors[i] + " played the role of " + roles[i] + BR);
/*for(var i = 0; i < size; i++) {
if ( favorite == actors[i]) {
found = true;
document.write("Your favorite actor " + actors[i] + " played the role of " + roles[i] + BR);
}
}
*/
if (!found) { //if we find nothing
document.write("Sorry, we couldn't find an actor with that name" + BR);
}
I have tried using for and also while loop but none work, in my head the while loop makes sense. So im not sure whats the issue.
You have to update some parts:
Please use another variable then i in the second loop
Move increase of counter to the end of scope of the second loop
Use SIZE in the second loop, as JS is case-sensitive.
Please check the updated example (https://codepen.io/alekskorovin/pen/xxXxYGB):
var SIZE = 4;
var actors = new Array(SIZE); //array holding actors
var roles = new Array(SIZE); //array holding roles
for (var i = 0; i < SIZE; i++) {
actors[i] = prompt("Please enter your " + (i + 1) + " favorite Actor");
roles[i] = prompt("What role did your " + (i + 1) + " Actor played?");
}
var favorite; // hold search actor name
var found = false;
var BR = "<br>";
favorite = prompt("Please enter the name of your most favorite actor of all");
let k = 0
while (k < SIZE && !found) {
if (actors[k] == favorite) {
found = true;
console.log(
"Your favorite actor " +
actors[k] +
" played the role of " +
roles[k] +
BR
);
if (!found) {
//if we find nothing
console.log("Sorry, we couldn't find an actor with that name" + BR);
}
}
k++;
}
found the problem thanks to #Teemu, a silly mistake I made
had SIZE declared but later down I was using size.

Why are null values inserted into the table?

I am trying to insert name and age into the HTML table using a prompt. But it inserts null values in the result, Can you implement a solution for this? Thank you in advance!
var i = 0;
var n = new Array();
var a = new Array();
var name = " ",
age = " ";
while (!(name == null || age == null)) {
name = prompt("Enter name: ");
age = prompt("Enter age: ");
n[i] = name;
a[i] = age;
i++;
}
document.writeln("<table border='1' width='25%'>");
document.writeln("<caption>Arrays</caption>");
document.writeln("<th>Name</th><th>Age</th>");
for (var k in n) {
if (!(k == null))
document.writeln("<tr><td>" + n[k] + "</td><td>" + a[k] + "</td></tr>");
}
document.write("</table>");
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accesses using numeric indexes (starting from 0).</p>
<p id="demo"></p>
That's because you are checking the null values before the prompt. Use the condition after name or age is provided.
while(true){
name=prompt("Enter name: ");
age=prompt("Enter age: ");
if(name==null || age==null) break;
n[i]=name;
a[i]=age;
i++;
}
The prompt function returns null on Cancel/Esc.
This is explained in the MDN documentation of prompt. To avoid printing null in your html table, you need to print it only if it exists.
Here is your code with the right condition:
var i = 0;
var n = new Array();
var a = new Array();
var name = " ",
age = " ";
while (!(name == null || age == null)) {
name = prompt("Enter name: ");
age = prompt("Enter age: ");
n[i] = name;
a[i] = age;
i++;
}
document.writeln("<table border='1' width='25%'>");
document.writeln("<caption>Arrays</caption>");
document.writeln("<th>Name</th><th>Age</th>");
for (var k in n) {
if(n[k] !== null && a[k] !== null)
document.writeln("<tr><td>" + n[k] + "</td><td>" + a[k] + "</td></tr>");
}
document.write("</table>");
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accesses using numeric indexes (starting from 0).</p>
<p id="demo"></p>

I am trying to create a calculator with javascript.

I can get the input from a user and i can put it all into a sum, but it retuns NaN.
my code:
var input1 = prompt("input 1","0");
var operation = prompt("operation","+");
var input2 = prompt("input 2","0");
var ans = (input1 + intput2);
if (operation = "+")
{
document.write("input1 + intput 2 = " + ans);
}
else
{
document.write("Other operations coming soon!");
}
There are couple of issues in this snippet.
You need to convert input1 & input2 if mathematical addition is expected. + sign before these variables are unary operator
There is a typo at intput2. In should me input2.
In the if condition validate using == or ===. operation = "+" is just assigning the value
var input1 = prompt("input 1", "0");
var operation = prompt("operation", "+");
var input2 = prompt("input 2", "0");
var ans = (+input1 + +input2);
if (operation == "+") {
document.write("input1 + intput 2 = " + ans);
} else {
document.write("Other operations coming soon!");
}
Prompt return the string so you need to convert the string to number using parseFloat() .And check the spell of input2 in var ans .
var input1 = prompt("input 1", "10");
var operation = prompt("operation", "+");
var input2 = prompt("input 2", "2");
var ans = parseFloat(input1) + parseFloat(input2);
if (operation = "+") {
document.write("input1 + intput 2 = " + ans);
} else {
document.write("Other operations coming soon!");
}

My for loop doesn't work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I was trying to shorten the code for returning "NO ANSWER" when one of my prompts was left blank in the code below:
var name = prompt("What is your name?");
var age = prompt("What is your age?");
var address = prompt("What is your email address?");
var credit = prompt("What is your credit card number?");
var social = prompt("What is your social security number?");
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (arr[i] == "") {
arr[i] = "NO ANSWER";
}
}
alert("Your information is " + name + ", " + age + ", " + address + ", " + credit + ", and" + social + ".");
alert("Now the internet has all of your information. Have a nice day >:D");
however, the code doesn´t work. can someone tell me why?
The for loop does work and works as expected. You need to use array arr while printing or using those input variables. That's because when you do arr[i] = "NO ANSWER";, you actually set the array element to "NO ANSWER", not the original variables. See the following:
var name = prompt("What is your name?");
var age = prompt("What is your age?");
var address = prompt("What is your email address?");
var credit = prompt("What is your credit card number?");
var social = prompt("What is your social security number?");
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (arr[i] == "") {
arr[i] = "NO ANSWER";
}
}
alert("Your information is " + arr[0] + ", " + arr[1] + ", " + arr[2] + ", " + arr[3] + ", and" + arr[4] + ".");
alert("Now the internet has all of your information. Have a nice day >:D");
Try this instead. It seems that you are updating arr but you are not printing arr to the screen.
var name = prompt("What is your name?");
var age = prompt("What is your age?");
var address = prompt("What is your email address?");
var credit = prompt("What is your credit card number?");
var social = prompt("What is your social security number?");
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (arr[i] == "") {
arr[i] = "NO ANSWER";
}
}
alert("Your information is " + arr[0] + ", " + arr[1] + ", " + arr[2] + ", " + arr[3] + ", and " + arr[4] + ".");
I tried dry running the code with no address. following code works. The if statement need to change
testarr = function () {
var name = 'xxx';
var age = 10;
var address;
var credit = 252525;
var social = 564654;
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (!arr[i]) {
arr[i] = "NO ANSWER";
}
}
return arr;
//alert("Your information is " + name + ", " + age + ", " + address + ", " + credit + ", and" + social + ".");
//alert("Now the internet has all of your information. Have a nice day >:D");
}
var t = new testarr();
console.log ("Your information is " + t[0] + ", " + t[1] + ", " + t[2] + ", " + t[3] + ", and" + t[4] + ".")

How to write a javaScript function to enter 2 numbers through prompts and display the sum of those numbers in an alert?

I wanted to display this:
Enter your numbers:
1st :
2nd :
Answer :
I tried doing this:
var a = prompt("A : ", "");
var b = prompt("B : ", "");
function calc(a,b)
{
return a + b;
}
alert ("The addition is =" + calc(a,b);
To do it with only one prompt:
var numbers = prompt("Enter two numbers separated by a semi-colon: ", "");
var a = numbers.split(";")[0];
var b = numbers.split(";")[1];
function calc(a,b)
{
return parseFloat(a) + parseFloat(b);
}
alert ("The addition of " + numbers + " is = " + calc(a,b));
You just need to parse the return from the prompts
var a = prompt("A : ", "");
var b = prompt("B : ", "");
function calc(a,b)
{
return parseFloat(a) + parseFloat(b);
}
alert ("The addition is =" + calc(a,b));

Categories