I am getting value from a text field. I have one if and several else if statement.
The problem the last else if doesn't execute even if the condition is true.
If I change the last else if to if it executes and gives alert. When I change that back to else if the statement doesn't execute. The else if before that is fine as it's firing/executing on a particular condition.
function Valcheck()
{
var txtVal = document.getElementById("sometextField").value;
if(txtVal =="%")
{
alert("% is only allowed with other characters.");
return;
}
else if(txtVal.indexOf("%") != -1)
{
if((txtVal.indexOf('%')) != (txtVal.length-1))
{
alert(" % is only allowed at the end.");
return;
}
}
else if(txtVal.indexOf(",") != -1)
{
alert("Comma or comma separated values are not allowed.");
return;
}
else if(( txtVal.length >0) && (txtVal.indexOf("%") == -1))
{
alert("Please enter % at the end of the value.");
return;
}
else if( txtVal.length > 11 )
{
alert(" Value can't be greater than 11 characters.");
return;
}
}
Please help. Thanks
The problem is that if txtVal.length > 11, then either this is met:
else if(txtVal.indexOf("%") != -1)
or this is met:
else if(( txtVal.length >0) && (txtVal.indexOf("%") == -1))
So that it will never reach the else if( txtVal.length > 11 ). You need to change this:
else if(txtVal.indexOf("%") != -1)
{
if((txtVal.indexOf('%')) != (txtVal.length-1))
{
alert(" % is only allowed at the end.");
return;
}
}
to this:
else if(txtVal.indexOf("%") != -1 && txtVal.indexOf('%') != (txtVal.length-1))
{
alert(" % is only allowed at the end.");
return;
}
so that it doesn't "capture" the case where txtVal.indexOf('%') == (txtVal.length-1).
There isn't a limit to the number of if statements. The issue is that one of the previous if statements catches the case you're testing.
Go through each if statements for the case your testing and see if it's beging caught by a previous one.
This happens because your else if(txtVal.indexOf("%") != -1) is true (so, second if from the top), but condition for "if" inside it is not true (so it doesn't go to "return".
there is no way that the last 'else-if' be hit:
if the textVal has a '%' in it it will go to the second 'else-if'
and if it does not have '%' it will go to the one before the last one.
so the last if never be hit.
There is no limit to if else nesting. There is a logical barrier to getting to nested if else clauses. Look into using
switch(caseVariable){
case 1: document.write("caseVariable = " + 1);
break;
case 35: document.write("caseVariable = " + 35);
break;
default: break;
}
Related
I'm new to JavaScript, so I'm currently working on a script that is supposed to update a string called Wasl_Status. These are the for conditions I'm trying to check:
Here is my code so far:
if (analog2 == 0) {
return "Tamper Weight";
}
if ((analog1 == 0) && (speed == 0)) {
return "Parked Device Disconnected";
}
if ((analog1 == 0) && (speed > 0)) {
return "Moving Device Disconnected";
if ((ignition == true) && (speed == 0))
return 'Parked Engine On';
if ((ignition == false) && (speed == 0))
return 'Parked Engine Off';
if (speed > 0)
return "Moving";
}
When I test it, the Wasl_Status only outputs the first three conditions and it ignores all the last three conditions. How do I make it to check every condition and return all 6 values? What I read so far is to create an array but current instructions say I must do nested if statements. I hope my question is clear. Thank you.
While it's correct, what you're doing, I think it's easier to read and follow the code if you, in most cases, try to return the value at the end of the function:
var message = 'no statements fit';
if (analog2 == 0) { message = "Tamper Weight"; }
else if (analog1 == 0 && speed == 0) { message = "Parked Device Disconnected"; }
else if (analog1 == 0 && speed > 0) {
message = "Moving Device Disconnected";
if (ignition == true && speed == 0) { message = 'Parked Engine On'; }
else if (ignition == false && speed == 0) { message = 'Parked Engine Off'; }
else if (speed > 0) { message = "Moving"; }
}
return message;
Then you would see, in an easier way, what is returning and when:
if ((analog1 == 0) && (speed > 0)) {
return "Moving Device Disconnected";
// ... everything after this code will never be executed because the function "stops" executing after a return.
I ran the following code in Google Chrome Version 54.0.2840.100 (64-bit). It displays an alert dialog successively asking for input until the user enters the correct answer, but the problem is that when i click the close button or cancel button in the alert dialog instead of closing, it continues asking for input.Also the close button on the tab is unclickable.Nevertheless I can close chrome main window but is there a code to correct this.
var answer = Number(Math.floor(Math.random()*10));
do{
var number = Number(prompt("Guess a number"));
if(number-answer >10){
alert("Too big!!");
}
else if(number-answer < 10 && number>answer ){
alert("It's bigger, but you are close!");
}
else if(answer-number < 10 && number<answer){
alert("It's smaller, but you are close!");
}
else if(answer-number > 10){
alert("Too small!!");
}
else if(number==answer){
alert("You WIN !!");
break;
}
}while(number!=answer);
The easiest and straightforward answer would be to remove the do...while loop. 'coz that would keep the code running till you input the right answer.
So, you could check for the inputed number, if it is null break it, else convert it to your number and run the loop.
checking for null firsthand would make it easy to check for 0 as an input too
var answer = Number(Math.floor(Math.random()*10));
do{
var number = prompt("Guess a number");
if(number!=null){
number = Number(number);
} else {
break;
}
if(number-answer >10){
alert("Too big!!");
}
else if(number-answer < 10 && number>answer ){
alert("It's bigger, but you are close!");
}
else if(answer-number < 10 && number<answer){
alert("It's smaller, but you are close!");
}
else if(answer-number > 10){
alert("Too small!!");
}
else if(number==answer){
alert("You WIN !!");
break;
}
}while(number!=answer);
var answer = Number(Math.floor(Math.random()*10));
do{
var number = Number(prompt("Guess a number"));
if(number === 0){ // this check is needed
break;
}
if(number-answer >10){
alert("Too big!!");
}
else if(number-answer < 10 && number>answer ){
alert("It's bigger, but you are close!");
}
else if(answer-number < 10 && number<answer){
alert("It's smaller, but you are close!");
}
else if(answer-number > 10){
alert("Too small!!");
}
else if(number==answer){
alert("You WIN !!");
break;
}
}while(number!=answer);
on closing the prompt, null is returned
passing null to Number function will return 0
hence the check for 0 is added
you could also modify the code as follows to allow 0 as input from the user
var input= prompt("Guess a number");
if(input === null){
break;
}
var number = Number(input);
... rest of the code
If click cancel, the input value will be null, then Number(null) will be 0.Unless the guess number is 0, the alert dialog would not be closed.
You'd better check the input value is null before cast it.
Window.prompt()
I have added a line of code to check whether user has cancelled the prompt.
var answer = Number(Math.floor(Math.random()*10));
do{
var number = Number(prompt("Guess a number"));
// Add the below code to check for null and exit
if (number === null)break;
// END
if(number-answer >10){
alert("Too big!!");
}
else if(number-answer < 10 && number>answer ){
alert("It's bigger, but you are close!");
}
else if(answer-number < 10 && number<answer){
alert("It's smaller, but you are close!");
}
else if(answer-number > 10){
alert("Too small!!");
}
else if(number==answer){
alert("You WIN !!");
break;
}
}while(number!=answer);
I am writing this basic control structure for a lesson and I am getting some unexpected behavior.
var answer = prompt('what is your age');
if (answer >= 21) {
alert('good to go!');
}
else if (answer < 21) {
alert('sorry not old enough');
}
else if (answer != typeof Number) {
alert('please enter your age as a number');
}
else if (answer === null) {
alert('you did not answer!');
}
On the very last conditional, I would expect that if I left the prompt empty, it would execute the last alert. However, it just says 'not old enough'. Is it treating no input into the prompt as 0? How can fix this?
Thanks.
Prompt doesn't return null if the user hits OK, to test for emptiness, you need to check if the string is empty answer === ""
You need to move the last two checks to the top since "" < 21 is true:
var answer = prompt('what is your age');
if (answer === '') {
alert('you did not answer!');
} else if (isNaN(answer)) {
alert('please enter your age as a number');
} else if (answer >= 21) {
alert('good to go!');
} else if (answer < 21) {
alert('sorry not old enough');
}
I have the following code. It works fine for blank fields, but it doesn't catch the other numeric exceptions. What am I doing wrong?
function validateForm() {
var a = document.forms["Form"]["percentage"].value;
var b = document.forms["Form"]["minutes"].value;
if (a == null || b == null || a == "" || b == "") {
alert("Please Fill All Required Field");
return false;
} else if (isNan(a) == true || isNan(b) == true) {
alert("Please enter valid numeric values");
return false;
} else if (parseInt(a) > 100) {
alert("Percentage can't exceed 100");
return false;
} else if (parseInt(b) < 0 || parseInt(a) < 0) {
alert("Values can't be negative");
return false;
}
}
Change this line:
else if((isNan(a)==true) ||(isNan(b)==true)){
to this:
else if (isNaN(a) || isNaN(b)) {
as the function is named #isNaN(). Using == true in conditionals is quite redundant, so I removed them.
I have also made a fiddle for you. It contains the fixed code, and it is working well.
Help! The if/elseif/else code block won't work! When the code reaches prompt "what will you do?" no matter what you type, you get all the alerts. It should come up blank when you type a command that is not in the if blocks, and give you an alert if you did type R, L or M. Typing F should give you no alert.
while (Room = 1) {
var Choice = prompt ("What will you do?");
if (Turn = "Start");
{
if (Choice = "F");
{
Turn = "1";
}
else if (Choice = "R");
{
alert ("You cannot do that...");
}
else if (Choice = "L");
{
alert ("You cannot do that...");
}
else if (Choice = "M");
{
alert (" 1"+'\n'+" 1" + '\n' + "221" + '\n' + " X");
}
else
{
alert ("You cannot do that...")
}
}
Use == instead of =. A single equals is a variable assignment and evaluates to the result of the assignment. == is used for equality test.
Remove ; from your if and else if statement.
; represents end of statement
Also you can't use = as comparison operation, instead == or ===(strict comparison) as #Andy mentioned.
while (Room == 1) { // Actually your code fails at the beginning itself.
However I would suggest you to use switch for your case.
If you write "=" single equal to means assignment of value to that variable.
So, You should change the "=" Single equalto to "==" Double equalto for conditional purpose.
And If else has no end ";" Semi-Colon required in Javascript. removed it.
I have updated the following please try it.
while (Room == 1) {
var Choice = prompt ("What will you do?");
if (Turn == "Start")
{
if (Choice == "F")
{
Turn == "1";
}
else if (Choice == "R")
{
alert ("You cannot do that...");
}
else if (Choice == "L")
{
alert ("You cannot do that...");
}
else if (Choice == "M")
{
alert (" 1"+'\n'+" 1" + '\n' + "221" + '\n' + " X");
}
else
{
alert ("You cannot do that...");
}
}
}
You have a semicolon after all your if-elseif-statements. So regardless of what the boolean is inside the if, the if block is empty. Just remove semicolons and you're good to go.
With this:
if(1 == 1);
{
alert('Nope');
}
the block after if-statement is always executed because of the semicolon ending the if.
if(1 == 1)
{
alert('Yup');
}
Works.
Java scrip don't consider single '=' it works with '=='
try
if (Turn == "Start");
Instead of
if (Turn = "Start");
Remove semicolons ; at the end of the if and else if loops
and also compare string by using ==, not =
Replace your code with this one
while (Room = 1) { //here Room is int variable
var Choice = prompt ("What will you do?");
if (Turn == "Start")
{
if (Choice =="F")
{
Turn = "1";
}
else if (Choice == "R")
{
alert ("You cannot do that...");
}
else if (Choice == "L")
{
alert ("You cannot do that...");
}
else if (Choice == "M")
{
alert ("1" + '\n' + "1" + '\n' + "221" + '\n' + "X");
}
else
{
alert ("You cannot do that...")
}
}
Also, besides using strict comparison I would strongly suggest writing left curly brace just after if(...) not in the new line:
Like:
if(...){
Instead of:
if(...)
{
Reason for that is JavaScript's built-in semi-colon insertion, so sometimes it can produce silent errors or unexpected behavior. In some other programming languages it doesn't matter, but in JavaScript it does.