How can I set an empty alert - javascript

I have made a little game in Script. That's sort of arithmetic game. I asked 2+2-3=? and user have to give the answer. If the answer is right than alert will show congratulations and if answer is wrong then you are higher or lower than actual answer. But now I want to add another alert if someone not answering this question and leave the prompt empty and press enter than another alert will be display like You are looser. My question is; how can I set the value empty and alert. Here is what I tried and it didn't work. Please see the code below:
<script type="text/javascript">
var number = prompt("count these numbers: 2+5-10+8=?");
if (number == 5) {
alert("Congratulations Your Answer is Correct");
} else if (number > 5) {
alert("Your answer is a little higher.");
} else if (number < 5) {
alert("Your answer is little lower than actual answer.");
} else if (number == "null") {
alert("You are looser!");
}
</script>

I would parse the number so it's actually a Number type, instead of relying on the == to coerce the value for you. Then, you could check for NaN with the isNaN function, or better yet, leave off the if completely and just make it an else:
var number = parseInt(prompt("count these numbers: 2+5-10+8=?"), 10);
if (number === 5) {
alert("Congratulations! Your answer is correct.");
} else if (number > 5) {
alert("Your answer is a little higher.");
} else if (number < 5) {
alert("Your answer is little lower than actual answer.");
} else {
alert("You are a loser!");
}​
http://jsfiddle.net/KebNN/

Just compare it to an empty string:
if (number == '') {
// ...
Also, if you want to alert the same message on "Cancel" clicks, you can simply check whether number evaluates to false:
if (!number) {
// ...

Use (answer == null || answer == undefined || answer == '')

try:
} else if (number == "" || isNaN(number)) {
alert("You are looser!");
}

I'm not sure I understand the question, but is this what you're looking for?
alert("");

If the user presses cancel on a prompt, the value will be null. By comparing it with ===, we make sure the answer isn't 0 (0 == null is true).
<script type="text/javascript">
var number = prompt("count these numbers: 2+5-10+8=?");
if (number === null) {
alert("You are loser!");
} else if (number == 5) {
alert("Congratulations Your Answer is Correct");
} else if (number > 5) {
alert("Your answer is a little higher.");
} else if (number < 5) {
alert("Your answer is little lower than actual answer.");
}
</script>​

You have accounted for all of the possible results except for null you could just add a else at the end of the first if statement as a catch all.. I.E. if the user leaves it blank or enters an invalid character.
if( number == 5 ) {
alert( "Congratulations Your Answer is Correct" );
} else if ( number > 5 ) {
alert( "Your answer is a little higher." );
} else if ( number < 5 ) {
alert( "Your answer is little lower than actual answer." );
} else {
alert("You are looser!");
}
.....

Related

Find the output using typeof function

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

Javascript not running "else" or "===" but works for "if" and "else if"

Hello I'm new to javascript and trying to run the following
var age = prompt("What is your age");
if (age < 19) {
document.write("You can't drink");
}
else if (age === 19) {
document.write("you can finally drink");
}
else (age > 19) {
document.write("you can already drink");
}
I can't seem to get anything to show up but if I change my code to remove the else statement and change the === to just == my code runs. This is how it looks like when it runs after I get rid of the else statement and === operator.
var age = prompt("What is your age");
if (age < 19) {
document.write("You can't drink");
}
else if (age == 19) {
document.write("you can finally drink");
}
I'm trying to get the first block of code to run but can't. The page is empty and no prompt shows up. Someone please help.
There are a few mistakes in your code:
1) prompt method return string no number, so :
Use == instead of === :
else if (age == 19) {
PS: (19 == '19'); is true but (19 === '19'); is false
OR convert age to number :
else if (Number(age) === 19) {
2) You should not use condition for else , so you must change else like this:
else { document.write("you can already drink"); }
var age = prompt("What is your age");
if (age < 19) { document.write("You can't drink"); }
else if (Number(age) === 19) { document.write("you can finally drink"); }
else { document.write("you can already drink"); }
Your problem is the last else statement. You are putting a condition after the else, which does not work. You only add the condition after another if. You can fix this by removing the condition like so:
var age = prompt("What is your age");
if (age < 19) {
document.write("You can't drink");
}
else if (age === 19) {
document.write("you can finally drink");
}
else {
document.write("you can already drink");
}
You seem to be having some logical error in your last else statement. If none of the first 2 conditions are true, then logically speaking, the last condition must be true. else does not hold any conditions. It's simply just else in terms of the previous condition(s). Else you would have to use else if() again, but as mentioned earlier, in case neither of the conditions are true, then the last condition must be the case regardless in this example. Therefore, just else makes the most sense.
Example:
if (age < 19) {
document.write("You can't drink");
}
else if (age === 19) {
document.write("you can finally drink");
}
else {
document.write("you can already drink");
}
Another thing in terms of your operators. == means equal to, and can be used to compare different types. I.e. you can compare a number type to a string type, and if they both hold the same value, the statement will be true. However, === is a strict equals, and means that the things being compared must be the same value AND the same type.
Example:
var x = 5; //number
var y = '5'; //string
if(x == y) {
//true, because they are equal, both has the value 5
}
if(x === y) {
//false, because even though they are equal in value, they are not the same type
}
var a = 8; //number
var b = 8; //number
if(a === b) {
//true, because they are both equal, and the same type
}
So, to clearify,
== checks if the values are equal, no matter the type.
=== checks if the values are equal AND are of the same type.
More simple documentation on operators here.
Firstly you need to understant differnce between "==" and "===" . From this you can conclude
JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:
Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
Two Boolean operands are strictly equal if both are true or both are false.
Two objects are strictly equal if they refer to the same Object.
Null and Undefined types are == (but not ===). [I.e. (Null==Undefined) is true but (Null===Undefined) is false]
And secondly "else" with a condition is always written as "else if" ...else is block which is runs when none of its above conditions is true i.e none is true ..read from here for more information

Prompt user for entry, thank them for entry Javascript

The first prompt shows up, and nothing else happens, even if I enter a number or try to push through the prompt without entering anything.
So far I've written this code:
var ratingEntry = prompt("We would like for you to review . Please enter a
rating between 0.0 - 5.0?");
if (ratingEntry === undefined) {
prompt('Please enter a rating from 0-5!');
} else if (ratingEntry === 0) {
teacherRatings.push('ratingEntry');
prompt('Thank you!');
} else if (ratingEntry === 1) {
teacherRatings.push('ratingEntry');
prompt('Thank you!');
}
I've tweaked it several times to no avail.
The problem you have is that prompt return a string and you do check for equality without type coersion.
1 === 1 is true
"1" === 1 is false
Basically "1" is a string, and 1is a integer.
Change ===to == and you would ignore "type" check. Or just check for "1" instead of 1
To compare Integer you need to first parse ratingEntry into Integer then compare and for first condition It is coming blank not undefined so put both check with OR in first condition.
var ratingEntry = prompt("We would like for you to review . Please enter a rating between 0.0 - 5.0?");
if (typeof ratingEntry === undefined || ratingEntry.trim() == '') {
prompt('Please enter a rating from 0-5!');
} else if (parseInt(ratingEntry) === 0) {
teacherRatings.push('ratingEntry');
prompt('Thank you!');
} else if (parseInt(ratingEntry) === 1) {
teacherRatings.push('ratingEntry');
prompt('Thank you!');
}
and last thing I am not sure what you are doing with this code but It should be like this
Use
teacherRatings.push(ratingEntry);
Instead of
teacherRatings.push('ratingEntry'); //this push ratingEntry as string in teacherRatings not as a value of variable
You may want to parse the input to Float and then use a while loop until the input is valid:
var ratingEntry = prompt("We would like for you to review . Please enter a rating between 0.0 - 5.0?");
var ratingNum = parseFloat(ratingEntry)
while (isNaN(ratingNum) || ratingNum < 0 || ratingNum > 5) {
ratingNum = parseFloat(prompt('Please enter a rating from 0-5!'));
}
teacherRatings.push(ratingNum);
prompt('Thank you!');
A prompt will return a string. And you need to always capture it to compare, so I would do:
var message = "We would like for you to review . Please enter a rating between 0.0 - 5.0?";
while(ratingEntry = prompt(message)) {
if (ratingEntry === '' || ratingEntry < 0 || ratingEntry > 5) {
message = 'Please enter a rating from 0-5!');
} else {
break;
}
}
etc. because you are using === which compares value as well as type (e.g. 1 === 1 and 1 !== '1', but 1 == '1')

check if input form value (int) is less than expected

My question is about validating a form. I am doing a validation of two fields, one of them receives the value in decimal, example ($ 500.00), is already with mask.
In this field that receives the value, it can not be less than 300.00.
If it is smaller 300.00, a message will appear saying the value has to be greater than 300.00.
Summary: The validation checks that it is empty, but does not check if the (number) int is less than $ 300
I'm using it this way (there's more code, in short):
function valid_simulation(form1) {
if (form1.valor.value == ' ') {
alert("value is not valid");
return false;
}
if (form1.valor.value <= 300) {
alert("value is not valid");
return false;
}
}
Thanks for any help.
Your basic concept is correct: set the message when the if statement test is falsy. Something like the following:
function showFormError(message) {
$("#alertBox").text(message)
}
if (isInvalid) { showFormError("We have a problem.") }
If the dollar mark is the issue, You can split it and validate.
var userInput = $("#inputData").val();
if(userInput.includes("$")) {
var splitArray = userInput.split("$");
if (typeof splitArray[1] && parseFloat(splitArray[1]) < 300){
alert("Amount Not valid");
}
}

Really basic javascript, checking a condition using || (or)

I am very new to JavaScript, and trying to learn using lynda.com.
I'm currently playing around with the if statement.
The code in question:
var value = prompt("1 or 2?");
if ( value == 1 ) {
alert("You have chosen 1.");
}
if ( value == 2 ) {
alert("You have chosen 2.");
}
if ( value != (1 || 2) ) {
alert("Invalid number. Try again.");
}
This is what i want to happen: If the number is NOT 1 or 2, i want JS to execute this piece of code:
if ( value != (1 || 2) ) {
alert("Invalid number. Try again.");
}
Apparently this is not the correct way to write it out, and i've tried writing it a bunch of different ways. Can someone show me the correct way, possibly using the else statement?
if ( value != 1 && value != 2) {
alert("Invalid number. Try again.");
}
If you write value != (1||2), the (1||2) will get first evaluated to 1 and then compared to value, so you effectively wrote:
if ( value != 1 ) { [...] }.
This is because the () have a higher predence than !=. You can also read this explanation about operator predence which gives more details.
1
if ( value != 1 && value !=2 ) {
alert("Invalid number. Try again.");
}
2
if ( !(value == 1 || value ==2) ) {
alert("Invalid number. Try again.");
}
3
if ( value == 1 ) {
alert("You have chosen 1.");
}
else if ( value == 2 ) {
alert("You have chosen 2.");
}
else {
alert("Invalid number. Try again.");
}
The best way to write this statement would be as follow:
if ( value == 1 )
{
alert("1");
}
else if ( value == 2 )
{
alert("2");
}
else
{
alert("no 1 or 2");
}
The if statement that you are messing on is (1 || 2)
What will happen is it will do a Boolean test and return 1.
it should look like this
if ( value !== 1 && value !== 2 )
{
alert("no 1 or 2");
}
Thanks
As already noted, the best is to separate into two NOT statements,and evaluate both:
if ( value != 1 && value != 2) ) {
alert("Invalid number. Try again.");
}
However, you could also use the if, else if, else pattern to cover yourself against all other inputs (letters, punctuation, whitespace, etc). The else acts as a catch-all at the end:
var value = prompt("1 or 2?");
if ( value == 1 ) {
alert("You have chosen 1.");
}
else if ( value == 2 ) {
alert("You have chosen 2.");
}
else {
alert("Invalid number. Try again.");
}
Inline statements like: (1 || 2) only evaluate the right hand side of the || if the left hand side is false-y. So what your statement actually is saying is:
if ( value != 1 )
Because 1 evaluates to true.
As most others have pointed out, what you actually want to do is:
if ( value != 1 && value != 2 )
The logic is incorrect. You have to do in this way
if ( value != 1 && value != 2) ) {
alert("Invalid number. Try again.");
}
the (1||2) statement is evaluated as 1 so you are testing if value != 1
have tried writing
if(value != 1 && value != 2)
You have to do it like
if ( value != 1 && value != 2 ) {
alert("Invalid number. Try again.");
}
OR
if (!(value == 1 || value == 2)) {
alert("Invalid number. Try again.");
}
You can use switch as follows
switch(value) {
case 1:
alert("You have chosen 1.");
break;
case 2:
alert("You have chosen 2.");
break;
default:
alert("Invalid number. Try again.");
}
Your problem is here:
if ( value != (1 || 2) )
What ths is doing is checking if "value" is not equal to (1 OR 2), where (1 OR 2) is evaluated first, because it's in the brackets. (1 OR 2) evaluates to 1, since 1 is truthy in javascript. What your code is actually doing is checking if your value is not equal to 1.
What you actually want to do is check if your value is !=1 and that your value is !=2. You do that like this:
if (value !=1 && value !=2) { /* do something */ }
You don't need a clause. You can just use:
else{
}

Categories

Resources