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

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{
}

Related

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')

javascript form validation textfield length

i got a problem on validate the student ID, it require 10 numbers, the problem i met is when i key in a valid student ID, it still return false. Please help me to check mycoding, thank you very much.
example of my Student ID = "1101106363"
if ((document.appsub.id.value == "") || !(isNaN(document.appsub.id.value)) || (document.appsub.id.value.length < 11))
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
update: [link]http://jsfiddle.net/rVswq/1/
You need to use document.getElementById method to select the element properly.
var el = document.getElementById("yourid");
if (!(isNaN(el.value)) || (el.value.length &lt 11))
{
alert("Please enter the correct Student ID");
el.focus();
return false;
}
There is something strange here.
You are checking if the value is null, OR if it IS a number (isNaN returns true if the value IS NOT a number, if you place !isNaN the result is true if the value IS a number), OR if the length is inferior to 11.
If you want to be sure that the inserted value is not null, a number and its length inferior to 11 you should write
if ((document.appsub.id.value == "") || isNaN(parseInt(document.appsub.id.value)) || (document.appsub.id.value.length > 10))
It looks to me like you don't need the NOT operator
if ((document.appsub.id.value == "") || isNaN(document.appsub.id.value) || (document.appsub.id.value.length < 11))
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
Your IF statement is wrong. You want:
if ( (document.appsub.id.value == "") || (isNaN(document.appsub.id.value)) || document.appsub.id.value.length < 11) )
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
Your if statement will catch students ids with length less to or equal to 10.
Test against length like 10 instead

checking numeric in javascript

I want to show the 'valid' message if the variable value is
not numeric with length of 10
an empty string ("")
if(isNaN(num) && num !="" && num.length!=10)
{
alert("invalid");
}
else
{
alert("valid");
}
But this code shows 'digits which length is not 10' as valid. But whether it is numeric or not numeric, if its length is not 10 it should be invalid.
Your Condtion placement is wrong here.
isNaN(num) && num !=""
here, for num=1234,isNaN is false(that means it is number), but the num!="" will give true resulting in Invalid alert.
Solution
replace && with || for OR condtion.
Did you mean this:
if(is_nan(num) && num !="" && num.length<10)
{
alert("invalid");
}
else
{
alert("valid");
}
Otherwise if length is <9 or >10, you will get false.
In this case you will alert valid when your num is non-numeric, nun-empty string with length >= 10.

JavaScript - validate numeric only and within range

I have an asp form which has a number of fields. On submit I want to check, using javascript that a tickbox has been selected and that an 'amount' field in within a given range AND has numbers only. I'm struggling to get it to check all three in one go - at the mometn i have the following:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["Amount"].value;
if (x<5 || x >250)
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
else if ( myForm.agreesubmit.checked == false )
{
alert ( "You Must Agree To The Terms and Conditions" );
return false;
}
}
</script>
At the moment this is two seperate checks for tick box select and range.
Any ideas appreciated.
Create a function that can do this:
function validate(str, chk, min, max) {
n = parseFloat(str);
return (chk && !isNaN(n) && n >= min && n <= max);
}
then call it like so:
function validateForm()
{
if(!validate(document.forms["myForm"]["Amount"].value,
document.forms["myForm"]["agreesubmit"].checked, 5, 250)) {
alert("Please complete all required fields - Amount you wish to save");
return false;
}
}
Try using the isNan(). Tutorial found at http://www.w3schools.com/jsref/jsref_isnan.asp
Something like:
if (isNaN(x) || x < 5 || x > 250))
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
Quick note you might be confused about the or/ands, so notice that the x<5 || x >250 is wrapped in () so that it can be partnered with the and numeric condition. Then, finally the whole if wraps the statements.
This will ensure it has numbers only first, then check the number against a range.
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["Amount"].value;
if( String(x).search(/^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/) != -1
&&( x<5 || x >250 ))
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
else if ( myForm.agreesubmit.checked == false )
{
alert ( "You Must Agree To The Terms and Conditions" );
return false;
}
}
</script>
via http://ntt.cc/2008/05/10/over-10-useful-javascript-regular-expression-functions-to-improve-your-web-applications-efficiency.html

How can I set an empty alert

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!");
}
.....

Categories

Resources