choice = input.questionFloat('\t1. Display all members\' information \n\t2. Display member information \n\t3. Add new member \n\t4. Update points earned \n\t5. Statistics\n\t6. Exit \n\t>> ');
if (choice.toString().includes('.')) {
console.log ('Please enter a valid input.');
}
choice contains the input from the user. If choice is a floating number, it will prompt the user that it is a invalid input. If there a better way of doing this instead of using .includes?
You can do that easily with JavaScript.
First take and convert to number and check if it's truthy value (non NaN) and check if it's not integer.
const num = Number('123.3')
if (num && !Number.isInteger(num)){
//float
}
Why not compare it to its value in int?
const intValue = 12
console.log(parseInt(value) !== value) // false => is an int
const floatValue = 12.1
console.log(parseInt(value) !== value) // true => is not an int
Related
I'm using the typeof command to make sure that only 1 of the 2 input fields of this temperature (Celsius to/from Fahrenheit) calculator is populated with data and it has to be a number. If the input is not a valid number or both fields are populated, the app will throw an error message.
The problem: nothing satisfies this condition - the errorMessage is always shown, even if I type in a valid number.
Is typeof the right solution to this problem? If it is, why is this code not working?
document.getElementById('temperature-form').addEventListener('submit', calculateResult);
function calculateResult(e) {
e.preventDefault();
const celsiusInput = document.getElementById('celsius');
const fahrenheitInput = document.getElementById('fahrenheit');
let resultOutput = document.getElementById('result');
// validate input data type and calculate result
if ((typeof celsiusInput === 'number') && (fahrenheitInput === null)) {
resultOutput.value = (celsiusInput.value * 1.8 + 32) + ' Fahrenheit';
} else if ((celsiusInput === null) && (typeof fahrenheitInput === 'number')) {
resultOutput.value = ((fahrenheitInput.value - 32)/1.8) + ' Celsius';
} else {
errorMessage('Please add a number in one of these fields');
}
}
Many thanks!
You could check the value properties of each input to see if they are numbers using the isNaN() function like so:
function calculateResult(e) {
e.preventDefault();
//Get the value of each input box
const celsiusValue = document.getElementById('celsius').value;
const fahrenheitValue = document.getElementById('fahrenheit').value;
//Get the result element
let resultOutput = document.getElementById('result');
// validate input data type and calculate result
if(!isNaN(celsiusValue) && (fahrenheitValue === null || fahrenheitValue === "")){
//Only celsiusValue has a valid number
resultOutput.value = (celsiusValue * 1.8 + 32) + ' Fahrenheit';
}else if(!isNaN(fahrenheitValue ) && (celsiusValue === null || celsiusValue === "")){
//Only fahrenheitValue has a valid number
resultOutput.value = ((fahrenheitValue - 32)/1.8) + ' Celsius';
}else if(!isNan(celsiusValue) && !isNan(fahrenheitValue )){
//Both contain a valid number
//Figure this one out as you didn't account for it
}else{
//Neither is a valid number
errorMessage('Please add a number in one of these fields');
}
}
Documentation of isNaN():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
When doing const celsiusInput = document.getElementById('celsius') you're getting the DOM Element, not the value.
In order to obtain de value you'd have to check for the property value.
So you'd end up with something like this:
const celsiusInput = document.getElementById("celsius")
const celsiusValue = celsiusInput.value
Now if we do typeof celsiusValue we'll always get string, because text/number inputs always accept text (check input's type property for more info).
The proper way to check if there are numbers or letters is using Regular Expressions.
I'll leave a simple example to act as a starting point for you:
const celsiusInput = document.getElementById("celsius")
const celsiusValue = celsiusInput.value
if(/\D/.test(celsiusValue)) {
alert("There is something that's not a number in the Celsius input!")
}
First of by doing a comparison like this fahrenheitInput === null you're comparing a DOM element against the value null.
That will only evaluate to true if the DOM Element never existed.
Secondly the typeof method will always evaluate to a String on DOM element types, so again this will always be false.
To really get what you want you have to do a proper check
To check if both input fields are supplied, simply checking the length of the values will surface:
if(fahrenheitInput.length > 0 && celsiusInput.length > 0) //fail
If fahrenheitInput only is given:
if(!isNaN(Number(fahrenheitInput)) //convert
if celsiusInput only is given:
if(!isNaN(Number(celsiusInput)) //convert
Finally if all checks above don't check our, fail
Ask user for a number. Determine if the number is even or odd. I have my constants set and using modulo to figure this out. However I am stuck in an infinite loop and can't figure out why. I have my if statement in the loop as well as a break statement to get out, but still in an infinite loop.
HAVE TO USE A WHILE LOOP
// declare constants
const MODULO = 2;
const EVEN = 0;
const ODD = 1;
// declare variables
var enteredNumber;
var result;
// prompt user to enter an even number
enteredNumber = prompt("Enter an even number: ");
// convert user input into a number
enteredNumber = Number(enteredNumber);
// determine result of modulo equation
result = enteredNumber % MODULO;
// while loop to check if enteredNumber is even or odd
while (result === EVEN) {
document.write(enteredNumber + " is an even number <br/>");
enteredNumber = prompt("Enter an even number: ");
enteredNumber = Number(enteredNumber);
result = enteredNumber % MODULO;
if (result === ODD) {
document.write(enteredNumber + " isn't an even number");
break;
}
}
You can essentially one-liner this thing. You're already checking stuff with the while.
document.addEventListener('DOMContentLoaded', () => {
while (!(parseInt(window.prompt('Enter an even number', '2') || '1', 10) % 2)) { };
});
Why this works
Javascript has 'falsy' and 'truthy' values.
window.prompt('Enter an even number', '2')
This code prompts the user for a number. The result is a string (or null, if the user blanks out the prompt).
<a string or null> || '1'
If the user blanked out the prompt, it will return null. In Javascript we can use the or operator to choose between two things. null || '1' reads from left to right. The first thing is falsy so it chooses '1'.
If the user entered a number (like 10), we would get the number they entered as a string.
Then we parse the string to a number with parseInt.
Take that result and use the modulo operator % to divide by the operand and return the remainder. When you divide by 2 the remainder will either be 0 or 1. These are falsy/truthy values.
while(0) evaluates to false and breaks the loop. while(1) evaluates to true and continues the loop.
I have been looking to validate the data input to check whether it is a integer or a string. I looked around and saw some suggestions and typeof suggestions but nothing seems to work.
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
var mk1 = parseInt(mk1);
mark1.push(mk1);
If you want to check whether input string is not a number try this:
if (isNaN(parseInt(name, 10)) {
//name is String
} else {
//name is Number
}
use the === operator as below
if (mk1 === parseInt(mk1 , 10))
alert("mk1 is integer")
else
alert("mk1 is not an integer. May be String")
If you don't know that the argument is a number-
function isInt(n){
return Number(n)===n && n%1===0;
}
Try this way to find input type;
if(!isNaN(parseInt(mk1)))
// for integer
else if(!isNaN(parseFloat(mk1)))
//for float
else
// String
When you prompt() the user for data, you always get a string. If you want to check, whether it actually contains just a number, you can try this:
var value = prompt('...'),
num = parseInt(value, 10);
if (num == value) {
// ... it is an integer, use `num`
} else {
// ... it's not an integer (or not *just* an integer), use `value`
}
(or use parseFloat(value) for real numbers).
It's hard to say what are you trying to do really. You seem to declare var mk1 twice, which looks a bit strange. Also, even if parseInt fails (then returns NaN [Not a Number]) you add it to mark1, which is probably not what you want. Have a look at this:
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
mk1 = parseInt(mk1);
if (Number.isNaN(mk1) === false) {
mark1.push(mk1);
} else {
alert("mark 1 is not a number");
}
Use this function:
isNaN(parseInt(mk1))
It will return "true" if not a number, and "false" if a number
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
First of all,
What am i doing ?
I have to set the limit of emails in our product in webpage.It's handled with the javascript for validation.It handles upto 8 digit numbers fine. But in our QA team enters the more than 17 digit number in the text box of other email field.It throw the negative message.What can i do ???
My sample code is:
if(form.otherEmails) {
if(validEmailArray.endsWith(',')){
var otherEmailLength = validEmailArray.substring(0,validEmailArray.length-1).split(",");
var setLimitOtherEmail = window.parent.document.getElementById('setLimitOtherEmail').value;
if(setLimitOtherEmail == '-1'){
form.otherEmails.value = otherEmailLength;
}
else if(otherEmailLength.length <= setLimitOtherEmail){
form.otherEmails.value = otherEmailLength;
}
else{
alert("More than "+setLimitOtherEmail+ " " +"Recipient emailIds not allowed in this section.\nIf you want to send it to more recipients, Please create a Bulk Contact Group.");
form.otherEmails.focus();
return false;
}
}
else
form.otherEmails.value = validEmailArray;
}
This is due to the limit being a string, and when a string is being compared to a number (length) the number is coerced into a string, not the other way around.
These are then compared lexicographically - and lexicographically "9" is more (>) than "19".
You need to use parseInt(setLimitOtherEmail, 10) to get the value as a number before comparing them.
Try parsing each of the numbers into Integers before performing any comparison operations on them.
var setLimitOtherEmail = parseInt(window.parent.document.getElementById('setLimitOtherEmail').value);
Other than that are you certain otherEmailLength is actually the number that you want? From the looks of it you are taking the substring of validEmail array and splitting it on "," but it doesn't look like you actually get the length of the array. Try adding .length to the end of the value of otherEmailLength.
var otherEmailLength = validEmailArray.substring(0,validEmailArray.length-1).split(",").length;