Having confusion regarding how to pass value in a var through prompt - javascript

<script>
var p=prompt("how old are you","");
if(p)
alert(p+" is your age");
else
alert("You dint entered any input or you have entered a non-integervalue");
</script>
This is my javascript code. Suppose i enter my age 0.
Then p=0 this implies the else part of the code will execute. But the code is executing the if part!
Why is it happening?
I'm new to Web-development , Please Help.
Thank You!

parseInt() the result of the prompt, that means, parsing the string result to an integer
Now, if the input is "0", it is parsed to 0, and 0 == false.
Thus the "else" condition would take place, as required.
Also, if a non-integer string is entered, such as alphabets, the result would be a NaN and the else part would occur
var p=parseInt(prompt("how old are you",""));
if(p) {
alert(p+" is your age");
}
else {
alert("You dint entered any input or you have entered a non-integervalue");
}

Just write this code :
var p=prompt("how old are you","");
alert(typeof(p));
You will see that it is a string. "0" is a string, so it will be evaluated to true as it is not empty or null.
So, parse it to a number before doing anything.

If you want to ensure the prompt input is number, you should use isNaN function to check the input.
var p=prompt("how old are you","");
if(!isNaN(p)) alert(p+" is your age");
else alert("You dint entered any input or you have entered a non-integervalue");

Related

Testing to see if entered input is a number (JavaScript)

(inputField was defined earlier as the html inputfield)
No matter what input I enter in the inputField, it will always alert 'good job!'. The code worked perfectly earlier, but I changed like one line and now I can't figure out how to fix it. Triple equality signs === don't work either.
let input = inputField.value;
var amount = parseInt(input);
if(amount == NaN || amount == undefined){
alert('enter a valid number!');
} else{
alert('good job!');
}
Try trpeof to get the type of the amount.
console.log(typeof(amount))
Or to get a boolean value just use isNan.
console.log(isNaN(amount))
To check if amount is a number or not use isNaN(amount)

Boolean logic interpretation in google chrome console

I'm having difficulties figuring out why the code below doesn't work as expected:
const userInput = prompt("Enter something");
if (userInput) {
console.log("TRUTHY");
} else {
console.log("FALSY");
}
I keep getting "TRUTHY" no matter what I do. I understand the logic of this code and even when running the source file from the class I'm not getting the expected output.
I should get "FALSY" whenever the input is: 0, null, undefined, an empty string or NaN.
What am I doing wrong?
Thank you.
Edit 1: Turns out I was getting ahead of myself. The code should in fact return "TRUTHY" unless you input an empty string.
Which browser are you using? because when I run this code on ms edge, it returns FALSY when I enter nothing. Also, userInput is set to a string type by default, and the string "0" is true as it contains something. You'll have to use parseInt() to convert the value to an integer, though that doesn't look like what you want to do. Consider looking for syntax errors, and check if your browser is up to date.
Since userInput is a string we have to check its length to find out whether it is empty
const userInput = prompt("Enter something");
if (userInput.length !== 0 && userInput == 0 && userInput == null && userInput == NaN) {
console.log("TRUTHY");
} else {
console.log("FALSY");
}
Change that if() to:
if (userInput == true) {
It's because the if(), as you have it, does a strict equality (===), so object types much match.

A question about a little gusess the age game i made with Js

in my udemy course, we just got introduced to JS!
I love this language, and right now I'm pretty much a novice.
I hope you can help me, i want my code to keep asking the user to guess the age that I've set as the sercretNumber.
i got 2 problems :
1) I think my code can and need to be shorter maybe with some OR and AND.
2) I can't get it to tell the user that if the number is negative or above 100, to prompt the user again for input by saying - Your number needs to be from 1-100.
I get it to work once and it's gone!
here's the Js code :
var secretNumber=98;
var numbGues=Number(prompt("Can you guses My age? (Hint - its 1-100"))
while (numbGues!=secretNumber){
// here I want this message to keep repeating if the user enters a non-valid input such as: -987 , or 54564654//
if (numbGues<0 || numbGues>100 ){
var numbGues=Number(prompt("Pleae choose a valid number between 1-100"))
}
if (numbGues<secretNumber){
var numbGues=Number(prompt("Too low! try again"))
}
else if (numbGues>secretNumber) {
var numbGues=Number(prompt("Too High! Try again!"))
}
if (numbGues==secretNumber) {
alert("You guessed it!")
}
}
Think about the if, if - else if, if structure you have here. It's possible to streamline it. Once you've covered all bases, you don't need another if, you just need an else to end the conditional statement.
As to your second point, in your first if statement, you're already prompting the user for the very same situation you mentioned. Just replace it with the error message you want to be displayed in that block.
little bit changed your code. you need to change
if (numbGues==secretNumber) {
alert("You guessed it!")
}
this if statement. finally your code looks like this.
var secretNumber=98;
var numbGues=Number(prompt("Can you guses My age? (Hint - its 1-100"));
while (numbGues!=secretNumber){
// changed if else statements
if (numbGues<0 || numbGues>100 ){
numbGues=Number(prompt("Pleae choose a valid number between 1-100"));
}else if (numbGues<secretNumber){
numbGues=Number(prompt("Too low! try again"));
}else if (numbGues>secretNumber) {
var numbGues=Number(prompt("Too High! Try again!"));
}
}
//you need to check this if statement in here otherwise if user entered secret number first time didn't show any alert
if (numbGues==secretNumber) {
alert("You guessed it!")
}

javascript variables always not equal

I have two variables, totalGuess and condensedAnswer. I am creating a jQuery click event and if totalGuess doesn't equal condensedAnswer then the click event will not occur and a div called message will display the message "Sorry, but your answer is incorrect. Please try again."
The problem is, totalGuess in the if statement is never equal to condensedAnswer. I've tried seeing typeof and they are both strings. I've tried console.log(totalGuess+"\n"+condensedAnswer); and they both return the same value. I've tried hardcoding the condensedAnswer, and totalGuess was able to be equal to the hardcoded answer. But when I tried comparing condensedAnswer with the hardcoded answer, it's not equal, even though the console.log value for condensedAnswer is the same. I'm not what's wrong.
Here's the code snippet:
$('.submitGuess').click(function(e){
var totalGuess = "";
var condensedAnswer = answer.replace(new RegExp(" ","g"), "");
$('.crypto-input').each(function(){
totalGuess += $(this).val();
});
// if incorrect guess
if(totalGuess !== condensedAnswer) {
$('.message').text("Sorry, but your answer is incorrect. Please try again.");
e.preventDefault();
}
// if user wins, congratulate them and submit the form
else {
return true;
}
});
If it helps, here's the page, just a random test cryptogram plugin for Wordpress:
http://playfuldevotions.com/archives/140
The problem has nothing to do with the check. The problem is the fact your value you are checking against has hidden characters. However you are getting that string has the issue.
Simple debugging shows the problem
> escape(totalGuess)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158"
> escape(condensedAnswer)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158%00"
It has a null character at the end.
Now looking at how you fill in the answer you have an array with numbers
"071,111,100,039,...49,053,056,"
Look at the end we have a trailing comma
when you do a split that means the last index of your array is going to be "" and hence why you get a null.
Remove the trailing comma and it will magically work.

Check validation for numbers only

following is my piece of code which checks if the input format is EMAIL which comes from the form input or not and validates accordingly i want to know how can i modify the following code that validates if the input was only number
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
Use jQuery's IsNumeric method.
http://api.jquery.com/jQuery.isNumeric/
$.isNumeric("-10"); // true
if (email.match(/[0-9]+/)) {
//it's all numbers
}
EDIT
As mentioned in the comments, to ensure that the entry is ALL numbers, the regex would have to include the begin and end characters, ^ and $:
if (email.match(/^[0-9]+$/)) {
//it's all numbers
}
Or even more succinctly:
if (email.match(/^\d+$/)) {
//it's all numbers
}
I don't deserve the credit for that fix, but I did want to correct it for anyone who may come find this later.
I would use:
if(isNaN(email*1)){
//evaluated to NaN
}else{
//evaluated to number
}
In this case the (email*1) have the possibility to evaluate to NaN, and thus will fail the check because the list of falsish values are 0,"",false,null,undefined,NaN
Check if converting the email address to a Number object returns a 'Not a Number' value; if not, the input was a number. The code would look like this:
if(!isNaN(Number(email)) {

Categories