I have an input field thats only supposed to take numbers inbetween 1 and 4. If the number is inbetween 1 and 4, it runs some code. If not, it shoots an alert that tells the user to try again with a number between 1 and 4. Here is my code
var number = document.getElementById("num").value;
if(Number(number) === 1 || Number(number) === 2 || Number(number) === 3 || Number(number) === 4 ){
//success code here///
}
else if(Number(number) !== 1 || Number(number) !== 2 || Number(number) !== 3 || Number(number) !== 4) {
} alert("Please type a whole number between(and including) 1 and 4 into the input field.");
I learned that the '.value;' function returns a string, even if the value is a number. So I put the var 'number' in the Number(); function that converts it to a number.
The problem is, when I type 1 into the input field. It shoots the alert even though it equals 1. None of the other numbers work either. I checked the console, and there are no syntax errors(also according to DreamWeaver). Help would be highly appreciated :)
I think you made a simple mistake of putting your alert outside the else if clause.
However there are a few other things you can do to make that a little more readable and efficient.
// Call Number() here so you only have to do it once
var number = Number(document.getElementById("num").value);
// You can also do something like parseInt(document.getElementById("num").value)
// Now check to see if Number() or parseInt() actually parsed an integer out of their input
// and then check that if it's outside your number range
if (isNaN(number) || number < 1 || number > 4) {
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
} else {
// Do Successful code
}
we can write like this also
var patt1 = /[1-4]/g;
if(patt1.test(number)){
//success code here///
}
else{
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
}
Related
Here is a simple code snippet where I am ensuring the user input is a number and is between 1-3
do{
var choice = parseInt(prompt("Please select one of the following:\n1.ROCK\n2.PAPER\n3.SCISSORS\n[NOTE: Choose your selection by pressing a number between 1,2 or 3.]"));
}while(isNaN(choice) && (choice === 1 || choice === 2 || choice === 3));
While debugging I see the debugger does not even evaluate the part after && where I am keeping a check on the input to be among 1, 2 or 3
Weirdly enough, the do-while construct works fine if I just have :
do{
var choice = parseInt(prompt("Please select one of the following:\n1.ROCK\n2.PAPER\n3.SCISSORS\n[NOTE: Choose your selection by pressing a number between 1,2 or 3.]"));
}while(isNaN(choice));
Can someone tell me what am I missing here or doing wrong?
As your code looks now, you are looping as long as it's not a number and it's either 1, 2, or 3. Since those three are all valid numbers, the overall condition can never be true - if it's not a number then it won't be 1, 2 or 3, and if it's 1, 2 or 3 it won't be "not a number" (since it's a number).
From what you wrote, you want to keep looping if it's not a number or not one of those three:
do {
var choice = parseInt(prompt("Please select one of the following:\n1.ROCK\n2.PAPER\n3.SCISSORS\n[NOTE: Choose your selection by pressing a number between 1,2 or 3.]"));
} while (isNaN(choice) || !(choice === 1 || choice === 2 || choice === 3));
(I changed && to || and added a ! before the second part of the condition.)
However, since you are limiting it to three exact options anyway, you don't even need to check for NaN anymore, because as mentioned before, if it's 1, 2 or 3 it means it's not NaN anyway:
do {
var choice = parseInt(prompt("Please select one of the following:\n1.ROCK\n2.PAPER\n3.SCISSORS\n[NOTE: Choose your selection by pressing a number between 1,2 or 3.]"));
} while (!(choice === 1 || choice === 2 || choice === 3));
This becomes a bit easier to read by getting rid of the negation in the front, replacing === by !== and || by &&:
do {
var choice = parseInt(prompt("Please select one of the following:\n1.ROCK\n2.PAPER\n3.SCISSORS\n[NOTE: Choose your selection by pressing a number between 1,2 or 3.]"));
} while (choice !== 1 && choice !== 2 && choice !== 3);
An alternative way to simplify the previous code is to create an array with valid values and loop as long as this array doesn't include the actual input number:
do {
var choice = parseInt(prompt("Please select one of the following:\n1.ROCK\n2.PAPER\n3.SCISSORS\n[NOTE: Choose your selection by pressing a number between 1,2 or 3.]"));
} while (![1, 2, 3].includes(choice));
When the first statement of the while loop is false the compiler doesnt compile the other statements after && here in this example (choice === 1 || choice === 2 || choice === 3) because it doesn`t matter what the other statements result is. The while loop is not executed at all.
This is compiler optimation (Short-circuit evaluation) for more information look at this article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND
Assume that when you prompt a non-nan value e.g. a number, isNaN evaluates false, thereby going into short-circuit evaluation. However, I think you want to accept one of 1,2, or 3 values. So shouldn't it be like !(choice === 1 || choice === 2 || choice === 3)? If one of them equals that value, no need to loop again.
A less complicated approach (avoiding parseInt, isNaN and multiple boolean checks) may be (snippet for the whole game ;):
Play it here
document.querySelector('button')
.addEventListener( 'click', () => location.reload() );
let choices = ['ROCK', 'PAPER', 'SCISSORS']
let choice = 0;
while ( !choices[+choice-1] ) {
choice = prompt(
`1. ROCK; 2. PAPER; 3. SCISSORS`, `Enter 1, 2 or 3`);
}
const values = {
yours: choices[choice-1],
mine: choices[Math.floor(Math.random() * 3 )]};
const tie = values.yours === values.mine;
const iWin = values.yours === 'SCISSORS' && values.mine === 'ROCK' ||
values.yours === 'ROCK' && values.mine === 'PAPER' ||
values.yours === 'PAPER' && values.mine === 'SCISSORS';
console.log(`your choice: ${values.yours}, against: ${values.mine}. ${
tie ? 'Tied...' : iWin ? 'You lost' : 'You win!'}` );
<button>Again...</button>
I am writing a code. And here I have a problem how can I fix that. I have an input line, it takes a string or a number. So I need to check what is the output and get the answer. I need to give a simple solution. So I can't use functions or something like that.
let input = prompt('Enter your text.');
if (typeof input === "string") {
alert("You have string.");
} else if (typeof input === "number" && input > 30) {
alert("number more than 30");
} else if (typeof input === "number" && input < 30) {
alert("number less then 30");
}
prompt will always return a string.
If you want to check whether the string is composed purely of numerical values, you could use a regular expression:
if (/^[+-]?\d+(?:\.\d+)?$/.test(input)) {
// then it's purely numerical
const num = Number(input.trim());
// perform more operations on the number
} else {
// it's not composed of only numerical characters
}
If you don't want to use a regex, you can use Number alone, but then you'll also include values like Infinity which might not be desirable, and since Number('') gives 0, you'll have to check for that separately:
const num = Number(input);
if (input.trim().length && !Number.isNaN(num)) {
// then it's a number, use num
}
Another approach that I'd recommend is to avoid prompt entirely. Consider using a proper modal instead, such as a form with an input box and a submit button.
In such a case, if you want to require a numeric input, just do:
<input type="number">
I had a similar problem a few weeks ago and this is what I did:
function testNumber(test) {
if (isNaN(test) === false) {
console.log("this is a number");
} else {
console.log("this is not a number");
}
}
testNumber(4); // number
testNumber("4") // number
testNumber("string") // not a number
You can replace "test" for a variable if you don't want to use a function
if (isNaN(myVar) === false) {}
And you may want to add more checks if you want to differentiate between 4 and "4"
You can do
let input = prompt('Enter your text.');
if(isNaN(Number(input))){alert("You have string.")};
if (Number(input) > 30) {
alert("number more than 30");
} else if (Number(input) < 30) {
alert("number less then 30");
}
So it can change all Stringed-numbers to numbers and check if they are number with the isNaN function
I'm currently working on an assignment where a person must choose cave 1, 2 or 3. Everything works except the validation part. This function is used to see if the user put in a number lower than 1, higher than 3 or not even a number. I'm trying to use a while loop to fix my problem. I have tried putting a continue after between the third last and second brackets.
//Gets input from the user
guess = prompt("Which cave will you go in? 1, 2 or 3?");
valid(guess);
//Checks if the input is valid
function valid(number) {
while(isNaN(number) || number < 1 || number > 3){
alert("Please Try Again");
prompt("Which cave will you go in? 1, 2 or 3?");
if(number <= 1 || number >= 3){
break;
}
}
}
You need to store the second prompt return value in a variable.
Also, return value of prompt is always a string, so you need to parse it into an int too for proper comparison, although JS implicitly converts it for you.
//Gets input from the user
guess = parseInt(prompt("Which cave will you go in? 1, 2 or 3?"));
valid(guess);
//Checks if the input is valid
function valid(number) {
while(isNaN(number) || number < 1 || number > 3){
alert("Please Try Again");
let number = parseInt(prompt("Which cave will you go in? 1, 2 or 3?"));
if(number <= 1 || number >= 3){
break;
}
}
}
You are not storing the prompt input in the function. Here is the solution with some modifications:
//Gets input from the user
guess = prompt("Which cave will you go in? 1, 2 or 3?");
valid(guess);
//Checks if the input is valid
function valid(number) {
let guess = number;
while(isNaN(guess) || guess < 1 || guess > 3){
alert("Please Try Again");
guess = prompt("Which cave will you go in? 1, 2 or 3?");
if(!isNaN(guess) && guess <= 1 && guess >= 3){
break;
}
}
}
change this line valid(guess); to valid(parseInt(guess));
If the user enters nothing in the prompt box then also it is showing "The num is prime", I have put validation below. Also if I enter "1" in prompt box, it is still showing "The num is prime".
var Num = prompt("Enter the Number");
var flag = 0;
if (isNaN(Num)) {
alert("please enter valid number");
}
for (var i = 2; i < Num; i++) {
if (Num % 2 === 0) {
flag = 1;
break;
}
}
if (flag === 0) {
alert("The num is prime");
}
else if (flag === 1) {
alert("The num is not prime");
}
Annoyingly, isNaN("") returns false, as if "" were a number. To fix the problem with the empty prompt, you're gonna need to check that Num.length > 0
The isNaN function is not intended to be used to check whether or not something can be interpreted as a number. It's intended to check if the provided value is the specific NaN value. My suggestion would be to attempt to convert the prompted string into a number and see if that conversion was successful.
var Num = parseInt(prompt("Enter the Number"), 10);
if(Number.isNaN(Num)) {
alert("please enter valid number");
}
Please note: this will not ensure that all provided values will be valid. For example, parseInt("ABC123") will return NaN as expected, but parseInt("123ABC") will return 123 and ignore the subsequent "ABC".
Regarding the issue with 1s, the code you have provided appears to mark all odd numbers as prime. Assuming you have written the part that determines whether or not an odd number is prime, you could have a special case to say "if the number is 1, it's not prime." That's because for many purposes, 1 acts like a prime number. Obviously, it's not the most elegant solution, but... it works.
My exercise is to force a user to type a number and check that it is less than 100. I think I've done this well but there is another case I don't know how to do. If the user does not type any number in the space, the program should show something like "you must type a number". How should I write the code?
var number=prompt('enter a number');
if (number<100){
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
}else if(number>100){
document.write('type again');
}
You can determine if the users input is a valid number by using the isNaN function. I have also validated the blank character for you, as shown below.
var isValid = !isNaN(number) && number !== "";
Full snippet:
var number = prompt('enter a number');
number = number.replace(/\s/g, "");
var isValid = !isNaN(number) && number !== "";
if (isValid) {
if (number<100) {
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
} else if(number>100) {
document.write('type again');
}
} else {
document.write("Looks like you didn't enter a valid number");
}
https://jsfiddle.net/ezgn5cv5/
var number = null;
while (number !== 0 && !number || number >= 100) {
number = parseInt(prompt('Enter a number, less than 100'));
}
document.write(
number +
' is less than 100 by ' +
(100 - number)
);
This puts us in a loop for whether or not the number is a valid integer (I assumed that's what you wanted, but you could change this to float or something else), and under 100. Only when the user's input is valid will it go to the line to output.
The second condition for the while loop is !number. This basically tests for falsy conditions, such as NaN or null. If parseInt() can't figure out what the user typed in for a number, it will return NaN. And, of course, we initialized the number variable to null.
The first condition for while is number !== 0 is actually required because of the second condition which tests for falsy. 0 is falsy, but 0 is a valid number less than 100, so we need to make sure that we let 0 be valid. Conditionals like these short circuit. That means that they are processed from left to right, and any condition failing the test will immediately bypass the conditional block of code below. If number is 0, we know that the whole condition is false and we can move on.
The third condition simply ensures we're under 100 by re-prompting if we're not.
Also, I should note that document.write() has some issues. It's better to select an element on the page and set its text.
Remove all spaces .replace(/\s/g, "").
Detect if user input a number using parseFloat() if you want to allow
user to input decimal numbers like 5.254 or only integers using
parseInt() like 5.
Then detect if number > 100 or number < 100.
See this example:
var number = prompt('enter a number');
number = number.replace(/\s/g, ""); //remove all spaces
if (number != "") { // if not empty
if (parseFloat(number) == number) { // if decimal/integer number
if (number < 100) {
newnumber = 100 - number;
document.write(number + ' is less than 100 by ' + newnumber);
} else if (number > 100) {
//number = prompt('enter a number');
document.write('type again');
}
} else {
//number = prompt('enter a number');
document.write('you must type a number');
}
} else { // if empty input
//number = prompt('enter a number');
document.write('shouldn\'t be empty');
}